Commando War
There is a war and it doesn't look very promising for your country. Now it's time to act. You have a commando squad at your disposal and planning an ambush on an important enemy camp located nearby. You have N soldiers in your squad. In your master-plan, every single soldier has a unique responsibility and you don't want any of your soldier to know the plan for other soldiers so that everyone can focus on his task only. In order to enforce this, you brief every individual soldier about his tasks separately and just before sending him to the battlefield. You know that every single soldier needs a certain amount of time to execute his job. You also know very clearly how much time you need to brief every single soldier. Being anxious to finish the total operation as soon as possible, you need to find an order of briefing your soldiers that will minimize the time necessary for all the soldiers to complete their tasks. You may assume that, no soldier has a plan that depends on the tasks of his fellows. In other words, once a soldier begins a task, he can finish it without the necessity of pausing in between.
Input
There will be multiple test cases in the input file. Every test case starts with an integer N (1<=N<=1000), denoting the number of soldiers. Each of the following N lines describe a soldier with two integers B (1<=B<=10000) & J (1<=J<=10000). B seconds are needed to brief the soldier while completing his job needs J seconds. The end of input will be denoted by a case with N =0 . This case should not be processed.
Output
For each test case, print a line in the format, “Case X: Y”, where X is the case number & Y is the total number of seconds counted from the start of your first briefing till the completion of all jobs.
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
题目大意:你有n个部下,每个部下需要完成一项任务。第i个部下需要你花Bi分钟交代任务,然后他会立刻独立地、无间断地执行Ji分钟后完成任务。你需要选择交代任务的顺序,使得所有任务尽早执行完毕(即最后一个执行完的任务应尽早结束)。注意,不能同时给两个部下交代任务,但部下们可以同时执行他们各自的任务。
分析:直觉告诉我们,执行时间较长的任务应该先交代。于是我们想到这样一个贪心算法:按照J从大到小的顺序给各个任务排序,然后依次交代。
1 # include<cstdio> 2 # include<vector> 3 # include<algorithm> 4 using namespace std; 5 6 struct Job{ 7 int j,b; 8 bool operator < (const Job& x) const{ // 运算符重载。不要忘记const修饰符 9 return j>x.j; //从大到小排序 10 } 11 }; 12 13 int main(){ 14 int n,b,j,cas=1; 15 int i; 16 while(scanf("%d",&n) && n){ 17 vector<Job>v; 18 for(i=0;i<n;i++){ 19 scanf("%d%d",&b,&j); 20 v.push_back((Job){j,b}); 21 } 22 sort(v.begin(),v.end()); //使用Job类自己的 < 运算符排序 23 int s=0; 24 int ans=0; 25 for(i=0;i<n;i++){ 26 s += v[i].b; //当前任务的开始执行时间 27 ans = max(ans,s+v[i].j); //更新任务执行完毕时的最晚时间 28 } 29 printf("Case %d: %d ", cas++, ans); 30 } 31 return 0; 32 }
上述代码直接提交可以通过测试。
可是为什么这样会对呢?假设我们交换两个相邻的任务X和Y(交换前X在Y之前,交换后Y在X之前),那么这两个任务的完成时间有没有影响?(相邻交换法)
情况一:交换之前,任务Y比X先结束,交换之后X的结束时间延后,Y的结束时间提前,最终答案不会变好。
情况二:交换之前X比Y先结束,因此交换后答案变好的充要条件是:交换后X的结束时间比交换前Y的结束时间要早(交换后Y的结束时间肯定变早了)。这个条件可以写成
B[Y]+B[X]+J[X]<B[X]+B[Y]+J[Y],化简得J[X]<J[Y]。这就是我们贪心的依据。