POJ-1700 Crossing River
Crossing River
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 20117 | Accepted: 7491 |
Description
A group of N people wishes to go across a river with only one boat, which can at most carry two persons. Therefore some sort of shuttle arrangement must be arranged in order to row the boat back and forth so that all people may cross. Each person has a different rowing speed; the speed of a couple is determined by the speed of the slower one. Your job is to determine a strategy that minimizes the time for these people to get across.
Input
The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. The first line of each case contains N, and the second line contains N integers giving the time for each people to cross the river. Each case is preceded by a blank line. There won't be more than 1000 people and nobody takes more than 100 seconds to cross.
Output
For each test case, print a line containing the total number of seconds required for all the N people to cross the river.
Sample Input
1 4 1 2 5 10
Sample Output
17
Source
问题分析:
我们知道贪心算法在没次选择都要作出当前状态下的最优解。
不妨将原问题简化。
当只有一个人或两个人时,问题解很明显。
当只有三个人时,很明显最优解就是让最快的人将剩余两人分两次送过河。
当只有四个人时,就会出现几种情况。第一种:前两个人速度较快,后两个人速度较慢。第二种:只有第一个人速度快,其他人速度都比较慢。
这是最优解就有两种情况:
1.最快的和次快的过河,然后最快的将船划回来;次慢的和最慢的过河,然后次快的将船划回来,所需时间为:t[0]+2*t[1]+t[n-1];
2.最快的和最慢的过河,然后最快的将船划回来,最快的和次慢的过河,然后最快的将船划回来,所需时间为:2*t[0]+t[n-2]+t[n-1]。
2.最快的和最慢的过河,然后最快的将船划回来,最快的和次慢的过河,然后最快的将船划回来,所需时间为:2*t[0]+t[n-2]+t[n-1]。
并且可以通过分析以上情况都是那个状态下的最优解。
当人数>4人,我们就可以不断将问题简化,每次都送走最慢的两个人过河,问题的规模不断的减小2个,且问题具有无后效行。
并且可以算出这样通过不断解局部最优解是可以得到总问题的最优解的。
ac代码:
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 int a[1001]; 5 int compare(const int a,const int b) 6 { 7 return a<b; 8 } 9 int main() 10 { 11 int n; 12 cin>>n; 13 int i,j; 14 for(i=0;i<n;i++) 15 { 16 int Time=0; 17 int sum; 18 cin>>sum; 19 for(j=0;j<sum;j++) 20 cin>>a[j]; 21 sort(a,a+sum,compare); 22 int x=0,y=sum-1; 23 while(sum>0) 24 { 25 if(sum<3) 26 { 27 Time=Time+a[sum-1]; 28 break; 29 } 30 if(sum==3) 31 { 32 Time=Time+a[2]+a[0]+a[1]; 33 break; 34 } 35 if(2*a[x+1]<a[x]+a[y-1]) 36 { 37 Time=Time+a[x]+2*a[x+1]+a[y]; 38 sum=sum-2; 39 y=y-2; 40 } 41 else 42 { 43 Time=Time+2*a[x]+a[y-1]+a[y]; 44 sum=sum-2; 45 y=y-2; 46 } 47 } 48 cout<<Time<<endl; 49 } 50 return 0; 51 }