算法竞赛进阶指南---0x17(二叉堆)超市

题面

在这里插入图片描述

输入样例

4 50 2 10 1 20 2 30 1
7 20 1 2 1 10 3 100 2 8 2
5 20 50 10

输出样例

80
185

题解

  1. 我们可以用一个小根堆来维护一个利润最大的集合,将所有产品按保质期从小到大排序,每次加入商品,判断集合中的商品是否满足在保质期能否卖出,不满足就从堆顶删除一个元素(堆顶就是利润最小的元素)
  2. 这样每次在极限的情况下删除最小的利润,在不过期的情况下集合中所保证的就是利润最大

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>

using namespace std;
typedef pair<int, int> PII;
const int N = 1e4 + 10;


int main() {
    
    

    int n;
    while (cin >> n) {
    
    
        PII v[N];
        for (int i = 1; i <= n; i++) {
    
    
            cin >> v[i].second >> v[i].first;
        }
        sort(v + 1, v + 1 + n);

        priority_queue<int, vector<int>, greater<int>> pq;

        for (int i = 1; i <= n; i++) {
    
    
            pq.push(v[i].second);
            if(pq.size()>v[i].first){
    
    
                pq.pop();
            }
        }
        int res=0;
        while (pq.size()){
    
    
            res+=pq.top();
            pq.pop();
        }
        cout<<res<<endl;
    }


    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/113783940