其他分享
首页 > 其他分享> > 题解 UVA1316 【Supermarket】(贪心,二叉堆)

题解 UVA1316 【Supermarket】(贪心,二叉堆)

作者:互联网

思路

首先将\(n\)个商品按照过期从小到大顺序排序,按照时间顺序加入集合\(S\)中维护,如果第\(i\)天有多个商品未卖出且在当天过期,则优先将集合中价值小的商品取出集合。最终答案就为集合中元素的和。而集合\(S\)则可以用小根堆维护。

代码


#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>

using namespace std;

typedef pair<int,int> PII;

const int N = 10010;

int n;
PII dt[N];
priority_queue<int, vector<int>, greater<int>> heap;

int main(){
    while (cin >> n){
        for (int i = 1; i <= n; i++) cin >> dt[i].second >> dt[i].first;
        sort(dt + 1,dt + n + 1);
        for (int i = 1; i <= n; i++){
            if (heap.empty() || heap.size() < dt[i].first) heap.push(dt[i].second);
            else if (heap.top() < dt[i].second){
                heap.pop();
                heap.push(dt[i].second);
            }
        }
        int ans = 0;
        while (!heap.empty()){
            ans += heap.top();
            heap.pop();
        }
        cout << ans << endl;
    }
    return 0;
}


标签:UVA1316,PII,int,题解,Supermarket,过期,集合,dt,include
来源: https://www.cnblogs.com/wxy-max/p/13237652.html