超市(stl + 贪心)

链接

 按照过期时间从小到大排序(两个元素一组可以用pair,放在 vector里面,排序)

当前商品的个数 > 过期时间,把利润最小的替换出去(小根堆)

#include <bits/stdc++.h>
#define int long long
using namespace std;
int n;
priority_queue<int,vector<int>,greater<int>> heap;//小根堆
signed main(){
    //freopen("in","r",stdin);
    ios::sync_with_stdio(0);
    while(cin >> n){
        vector<pair<int,int>> p(n);
        for(int i = 0; i < n;i++)
            cin >> p[i].second >> p[i].first;//利润和过期时间,将时间排序
        sort(p.begin(),p.end());
        for(auto x : p){
            heap.push(x.second);//把利润存进去
            while(heap.size() >= x.first)//商品个数 大于等于 过期天数,题目说一天只能卖一个
                heap.pop();//出队列
        }
        int res = 0;
        while(heap.size())
            res += heap.top(), heap.pop();
        cout << res << endl;
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/xcfxcf/p/13508213.html