题目链接:https://www.acwing.com/problem/content/147/
题意:超市里有N件商品,每个商品都有利润pi和过期时间di,每天只能卖一件商品,过期商品(即当天di<=0)不能再卖。
求合理安排每天卖的商品的情况下,可以得到的最大收益是多少。
数据范围
0≤N≤10000,
1≤pi,di≤10000
输入样例:
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的商品,那么就不是那么容易操作了啊。这里就可以用到堆来排序了。
先把所有商品按照保质期升序排列,先把第一个放入堆中,依次遍历;如果di < size(堆的大小),那么就合法,如果di > size 那么就把堆里面价值最小的去掉;依次遍历完后堆里的元素就是所有合法的商品了。
代码实现:
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 1e4 + 5;
int main()
{
int n;
while(cin >> n){
vector<PII> g(n);
for(int i = 0; i < n; i ++ )
cin >> g[i].second >> g[i].first;
sort(g.begin(), g.end());
priority_queue<int, vector<int>, greater<int> > heap;
for(vector<PII>::iterator it = g.begin(); it != g.end(); it ++ ){
heap.push(it -> second);
if(heap.size() > it -> first) heap.pop();
}
int res = 0;
while(heap.size()){
res += heap.top();
heap.pop();
}
cout << res << endl;
}
return 0;
}