可以反悔的贪心——贪心+堆维护
Posted sympa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了可以反悔的贪心——贪心+堆维护相关的知识,希望对你有一定的参考价值。
P2949 [USACO09OPEN]Work Scheduling G
题目描述
Farmer John has so very many jobs to do! In order to run the farm efficiently, he must make money on the jobs he does, each one of which takes just one time unit.
His work day starts at time 0 and has 1,000,000,000 time units (!). He currently can choose from any of N (1 <= N <= 100,000) jobs
conveniently numbered 1..N for work to do. It is possible but
extremely unlikely that he has time for all N jobs since he can only work on one job during any time unit and the deadlines tend to fall so that he can not perform all the tasks.
Job i has deadline D_i (1 <= D_i <= 1,000,000,000). If he finishes job i by then, he makes a profit of P_i (1 <= P_i <= 1,000,000,000).
What is the maximum total profit that FJ can earn from a given list of jobs and deadlines? The answer might not fit into a 32-bit integer.
输入格式
* Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains two space-separated integers: D_i and P_i
输出格式
* Line 1: A single number on a line by itself that is the maximum possible profit FJ can earn.
输入输出样例
2 10 1 5 1 7
思路:
代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 int n; 4 struct node { 5 int d, p; 6 bool operator < (const node& x) const { return p > x.p; } 7 }; 8 bool cmp(node d1, node d2) { 9 if (d1.d == d2.d)return d1.p > d2.p; 10 else return d1.d < d2.d; 11 } 12 node a[100010]; 13 int main() { 14 std::ios::sync_with_stdio(false); 15 priority_queue< node >q; 16 long long sum = 0; 17 cin >> n; 18 for (int i = 1; i <= n; i++) { 19 cin >> a[i].d >> a[i].p; 20 } 21 sort(a + 1, a + 1 + n, cmp); 22 for (int i = 1; i <= n; i++) { 23 if (a[i].d <= q.size()) { 24 if (a[i].p > q.top().p) { 25 sum -= q.top().p; 26 q.pop(); 27 sum += a[i].p; 28 q.push(a[i]); 29 } 30 } 31 else { 32 sum += a[i].p; 33 q.push(a[i]); 34 } 35 } 36 cout << sum << endl; 37 return 0; 38 }
以上是关于可以反悔的贪心——贪心+堆维护的主要内容,如果未能解决你的问题,请参考以下文章