AcWing 145. 超市
超市里有N件商品,每件商品都有利润pi<?XML:NAMESPACE PREFIX = "[default] http://www.w3.org/1998/Math/MathML" NS = "http://www.w3.org/1998/Math/MathML" />pi和过期时间didi,每天只能卖一件商品,过期商品不能再卖。
求合理安排每天卖的商品的情况下,可以得到的最大收益是多少。
输入格式
输入包含多组测试用例。
每组测试用例,以输入整数N开始,接下来输入N对pipi和didi,分别代表第i件商品的利润和过期时间。
在输入中,数据之间可以自由穿插任意个空格或空行,输入至文件结尾时终止输入,保证数据正确。
输出格式
对于每组产品,输出一个该组的最大收益值。
每个结果占一行。
数据范围
0≤N≤100000≤N≤10000,
1≤pi,di≤100001≤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.将过期时间大于当前堆中商品的数量直接加入到堆中。2.当前待加入的商品的过期时间等于堆中商品的数量时,将堆顶的利润和当前商品比较,如果该商品利润大,就删除堆顶,加入该商品。注意:小于当前个数的商品补会出现,因为商品的加入顺序已经按时间从小到大排序了。
代码:
1.数组模拟小顶堆
1 #include <iostream>
2 #include <algorithm>
3 #include <cstring>
4 #include <vector>
5 using namespace std;
6 const int SIZE = 1e6;
7 int heap[SIZE], n;
8
9
10 void up(int p) {
11 while(p > 1) {
12
13 if(heap[p] < heap[p/2]) {
14 swap(heap[p], heap[p/2]);
15 p /= 2;
16 }
17 else break;
18 }
19 }
20
21 void Insert(int val) {
22 heap[++n] = val;
23 up(n);
24 }
25
26 int GetTop() {
27 return heap[1];
28 }
29
30 void down(int p) {
31 int s = p * 2;
32 while(s <= n) {
33 if(heap[s] > heap[s+1] && s < n) s++;
34 if(heap[s] < heap[p]){
35 swap(heap[s], heap[p]);
36 p = s, s = p * 2;
37 }
38 else break;
39 }
40 }
41 void ExTract() {
42 heap[1] = heap[n--];
43 down(1);
44 }
45 void remove(int k) {
46 heap[k] = heap[n--];
47 up(k), down(k);
48 }
49 int main() {
50 int t;
51 cin >> t;
52 for(int i = 0; i < t; ++ i) {
53 int a;
54 cin >> a;
55 Insert(a);
56 }
57 return 0;
58 }
2.C++STL小顶堆(优先队列)
1 #include <iostream>
2 #include <algorithm>
3 #include <queue>
4 #include <vector>
5 using namespace std;
6
7
8 typedef pair<int,int> PII;
9
10 int main() {
11 int n;
12 while(cin >> n) {
13 vector<PII> p(n);
14 for(int i = 0; i < n; ++ i) cin >> p[i].second >> p[i].first;
15 sort(p.begin(), p.end());
16 priority_queue<int, vector<int>, greater<int>> heap;
17
18 for(auto i : p) {
19 heap.push(i.second);
20 if(heap.size() > i.first) heap.pop();
21 }
22 int res = 0;
23 while(heap.size()) res += heap.top(), heap.pop();
24 cout << res << endl;
25 }
26 return 0;
27 }
28
到此结束。
追求吾之所爱
浙公网安备 33010602011771号