AcWing 145. 超市(优先队列)

题目大意:有n个商品,每个商品有pi利润和di过期时间,每天只能卖一件商品,求最大利润。

题解:

将商品按过期时间从小到大排序。

建一个堆,里面存可以卖的商品,每加入一个商品后,如果heap.size()>di,说明已经超出该商品的保质期,

将堆中利润最小的那个商品删除。

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;

int n;

typedef pair<int,int> PII;


int main()
{
    while(cin>>n)
    {
        vector<PII>ve(n);
        for(int i=0;i<n;i++)
        {
            //scanf("%d%d",&ve[i].second,&ve[i].first);
            cin>>ve[i].second>>ve[i].first;
        }
        sort(ve.begin(),ve.end());
        priority_queue<int,vector<int>,greater<int>>heap;
        for(auto p:ve)
        {
            heap.push(p.second);
            if(heap.size()>p.first) heap.pop();
        }
        int ans=0;
        while(heap.size()) ans=ans+heap.top(),heap.pop();
        cout<<ans<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zzyh/p/14806025.html