Uva 11729 Commando War 貪心啦
阿新 • • 發佈:2018-12-23
Sample Input
3
2 5
3 2
2 1
3
3 3
4 4
5 5
0
Output for Sample Input
Case 1: 8
Case 2: 15
圖片摘自:https://me.csdn.net/SunnyYoona
思路:貪心,什麼交貪心呢?
貪心的思想就是區域性得到最優解再推廣到全域性。
這個題我們首先要知道的一點是一定要讓作戰時間長的隊員先執行,因為在他作戰的時間裡,還可以給別的隊員進行講述,這樣就節省了時間
假設我們現在已經有了一個最優的時間T,那麼我們判斷第i個士兵的時候只要取max(T-sum[i-1],b[i]+j[i] ) (sum[i-1]表示前i-1個b之和,因為講述的時間不能重合,也就是說不管怎樣都講述的時間之和都要包含在內,就看除了講述之和的時間剩下的時間比不比要第i個士兵的講述時間+作戰時間大就行了,你要保證任務都執行完肯定要取一個大的。)
化簡一下也就是比max (T,sum[i]+j[i] )
我說的太亂了,實在看不懂的話,就看程式碼吧
#include<iostream> #include<cmath> #include<algorithm> using namespace std; typedef struct node{ int b,j; }node; bool cmp(const node &a,const node &b) { return a.j>b.j; } int main() { std::ios::sync_with_stdio(false); node a[1005]; int n,i; int cnt=1; long long endtime,starttime; while(cin>>n&&n) { endtime=starttime=0; for(i=0;i<n;i++) cin>>a[i].b>>a[i].j; sort(a,a+n,cmp); for(i=0;i<n;i++) { starttime+=a[i].b; endtime=max(endtime,starttime+a[i].j); } cout<<"Case "<<cnt++<<": "<<endtime<<endl; } return 0; }