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
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; int main() { int t,n,x[1005]; cin>>t; while(t--) { cin>>n; for(int i=0;i<n;i++) cin>>x[i]; sort(x,x+n); int index=n,sum=0; //index 还有多少人没过河 sum 已用的秒数 while(index) //只剩3个人时直接推结果 { if(index==1) { sum+=x[0]; break; } else if(index==2) { sum+=x[1]; break; } else if(index==3) { sum+=x[1]+x[2]+x[0]; break; } else { sum+=min(2*x[1]+x[index-1]+x[0],2*x[0]+x[index-1]+x[index-2]); //1、 a和b出发,a回来,c和d出发,b回来 //2、 a和c出发,a回来,a和d出发,a回来 index-=2; } } cout<<sum<<endl; } return 0; }
-
« 上一篇:
C语言:搜索基础之迷宫问题
-
POJ - 3624 Charm Bracelet
:下一篇 »