1. 程式人生 > >NEFU 1265 (貪心+優先佇列)

NEFU 1265 (貪心+優先佇列)

最高獎勵

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

題意:中文題。

思路:因為過了截止時間,就不能再繼續做任務了。所以按照時間的升序排列,從後往前遍歷。將任務依次放入優先佇列中。

如果兩個任務之間的截止時間不相同,這時候在優先佇列裡面的都是滿足可以做任務的要求。取出隊首相加就行了。

程式碼:

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <algorithm>
  5. #include <queue>
  6. usingnamespace std;  
  7. struct node  
  8. {  
  9.     int e,w;  
  10.     friendbool operator <(node a,node b)  
  11.     {  
  12.         return a.w<b.w;  
  13.     }  
  14. }q[50005];  
  15. bool cmp(node a,node b)  
  16. {  
  17.     if(a.e!=b.e)  
  18.         return a.e<b.e;  
  19.     return a.w<b.w;  
  20. }  
  21. priority_queue<node> que;  
  22. int main()  
  23. {  
  24.     int n;  
  25.     while(~scanf("%d",&n))  
  26.     {  
  27.         while(!que.empty()) que.pop();  
  28.         longlong ans=0;  
  29.         for(int i=1;i<=n;i++)  
  30.         {  
  31.             scanf("%d%d",&q[i].e,&q[i].w);  
  32.         }  
  33.         sort(q+1,q+n+1,cmp);  
  34.         q[0].e=0;  
  35.         for(int i=n;i>=1;i--)  
  36.         {  
  37.             que.push(q[i]);  
  38.             if(q[i].e!=q[i-1].e)  
  39.             {  
  40.                 for(int j=1;j<=q[i].e-q[i-1].e;j++)  
  41.                 {  
  42.                     if(!que.empty())  
  43.                     {  
  44.                         ans+=(longlong)que.top().w;  
  45.                         que.pop();  
  46.                     }  
  47.                     elsebreak;  
  48.                 }  
  49.             }  
  50.         }  
  51.         printf("%lld\n",ans);  
  52.     }  
  53.     return 0;  
  54. }