超市里有 N 件商品,每件商品都有利润 pi 和过期时间 di,每天只能卖一件商品,过期商品不能再卖。
求合理安排每天卖的商品的情况下,可以得到的最大收益是多少。
输入格式
输入包含多组测试用例。
每组测试用例,以输入整数 N 开始,接下来输入 N 对 pi 和 di,分别代表第 i 件商品的利润和过期时间。
在输入中,数据之间可以自由穿插任意个空格或空行,输入至文件结尾时终止输入,保证数据正确。
输出格式
对于每组产品,输出一个该组的最大收益值。
每个结果占一行。
数据范围
0≤N≤10000,
1≤pi,di≤10000
最多有 14 组测试样例
输入样例:
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)用vector存pair, fisrt存天数、second存price并按天数排序
(2)遍历vector,将price存入小根堆中,如果堆的大小大于当前节点的天数,则去掉小根堆中最小的元素
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
typedef pair<int, int> PII;
int n;
int main()
{
while(cin >> n)
{
vector<PII> products(n);
priority_queue<int, vector<int>, greater<int>> heap;
for(int i = 0; i < n; i++) cin >> products[i].second >> products[i].first;
//first存日期,按日期排序
sort(products.begin(), products.end());
for(auto t : products)
{
heap.push(t.second);
if(heap.size() > t.first)
heap.pop();
}
int res = 0;
while(heap.size())
{
res += heap.top();
heap.pop();
}
cout << res << endl;
}
return 0;
}
并查集解法思路:
按照价值降序,每次扫描到一个价值,尝试一下在过期之前能不能卖出去;此时可能已经有比它更大价值的产品占用了一些日期,于是从过期时间往前面找,直到找到一个空位置。如果这个空位置大于0,那么就把这个产品安排在这天卖出。
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
typedef pair<int, int> PII;
const int N = 10010;
int p[N];
int n;
int find(int x)
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main()
{
while(cin >> n)
{
vector<PII> goods(n);
int Maxday = 0;
for(int i = 0; i < n; i++)
{
cin >> goods[i].first >> goods[i].second;
Maxday = max(Maxday, goods[i].second);
}
for(int i = 1; i <= Maxday; i++) p[i] = i;
sort(goods.begin(), goods.end());
int res = 0;
for(int i = n - 1; i >= 0; i--)
{
auto t = goods[i];
int r = find(t.second);
if(r > 0) // t < 0 表示没有空余天数了
{
res += t.first;
p[r] = r - 1;
}
}
cout << res << endl;
}
return 0;
}