NEFU 1265 (貪心+優先佇列)
阿新 • • 發佈:2019-01-01
最高獎勵
Problem:1265
Time Limit:1000ms
Memory Limit:65535K
Description
有N個任務,每個任務有一個最晚結束時間以及一個對應的獎勵。在結束時間之前完成該任務,就可以獲得對應的獎勵。完成每一個任務所需的時間都是1個單位時間。有時候完成所有任務是不可能的,因為時間上可能會有衝突,這需要你來取捨。求能夠獲得的最高獎勵。
Input
輸入包含多組資料。 每組資料第1行:一個數N,表示任務的數量(2 <= N <= 50000) 第2 - N + 1行,每行2個數,中間用空格分隔,表示任務的最晚結束時間E[i]以及對應的獎勵W[i]。(1 <= E[i] <= 10^9,1 <= W[i] <= 10^9)
Output
輸出能夠獲得的最高獎勵。
Sample Input
7 4 20 2 60 4 70 3 40 1 30 4 50 6 10
Sample Output
230
題意:中文題。
思路:因為過了截止時間,就不能再繼續做任務了。所以按照時間的升序排列,從後往前遍歷。將任務依次放入優先佇列中。
如果兩個任務之間的截止時間不相同,這時候在優先佇列裡面的都是滿足可以做任務的要求。取出隊首相加就行了。
程式碼:
- #include <iostream>
- #include <cstdio>
-
#include <cstring>
- #include <algorithm>
- #include <queue>
- usingnamespace std;
- struct node
- {
- int e,w;
- friendbool operator <(node a,node b)
- {
- return a.w<b.w;
- }
- }q[50005];
- bool cmp(node a,node b)
- {
- if(a.e!=b.e)
- return a.e<b.e;
-
return a.w<b.w;
- }
- priority_queue<node> que;
- int main()
- {
- int n;
- while(~scanf("%d",&n))
- {
- while(!que.empty()) que.pop();
- longlong ans=0;
- for(int i=1;i<=n;i++)
- {
- scanf("%d%d",&q[i].e,&q[i].w);
- }
- sort(q+1,q+n+1,cmp);
- q[0].e=0;
- for(int i=n;i>=1;i--)
- {
- que.push(q[i]);
- if(q[i].e!=q[i-1].e)
- {
- for(int j=1;j<=q[i].e-q[i-1].e;j++)
- {
- if(!que.empty())
- {
- ans+=(longlong)que.top().w;
- que.pop();
- }
- elsebreak;
- }
- }
- }
- printf("%lld\n",ans);
- }
- return 0;
- }