Crossing River
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 13580 | Accepted: 5193 |
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
n为1,2,3时,过河的最短时间能容易求出。现考虑n≥4的情况,将每个人的过河时间按从小到大的顺序排序,有ti ≤ tj, i < j。先把过当前河时间大的两个人先送到河对面,花费时间最少的方案是一下两种方案中花费时间小的那一个,
(1) 安排过河时间最小的人(t[0])和过河时间最大的人(t[n-1])过河,接着t[0]在对岸把船划回来,t[0]再和过河时间第二大的人(t[n-1])过河,最后t[0]再次把船划回来。
t=2*t[0]+t[n-2]+t[n-1]
(2) 安排过河河时间最小的人(t[0])和过河第二小的人(t[1])过河,接着t[0]在对岸把船划回来,安排过河时间第二大的人(t[n-1])再和过河时间最大的人(t[n])过河,最后t[n-1]将船划回来。
t=2*t[1]+t[0]+t[n-1]
分别计算后选择时间花费小的方案。而对于剩下的人,采用同样的处理方式。
1 #include <iostream> 2 #include <algorithm> 3 #include <map> 4 #include <vector> 5 #include <functional> 6 #include <string> 7 #include <cstring> 8 #include <queue> 9 #include <stack> 10 #include <set> 11 #include <cmath> 12 #include <cstdio> 13 using namespace std; 14 #define IOS ios_base::sync_with_stdio(false) 15 typedef long long LL; 16 const int INF = 0x3f3f3f3f; 17 const double PI=4.0*atan(1.0); 18 19 int t,n,ans,a[1005]; 20 21 int main() 22 { 23 scanf("%d",&t); 24 while(t--){ 25 scanf("%d",&n); 26 ans=0; 27 for(int i=1;i<=n;i++) scanf("%d",&a[i]); 28 sort(a+1,a+n+1); 29 int i; 30 for(i=n;i>3;i-=2){ 31 ans+=min(2*a[2]+a[1]+a[i],2*a[1]+a[i-1]+a[i]); 32 } 33 if(i==3) ans+=a[1]+a[2]+a[3]; 34 else if(i==2) ans+=a[2]; 35 else ans+=a[1]; 36 printf("%d ",ans); 37 } 38 }