Crossing River

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

题目意思:有n个人想过河,但是他们只有一条能同时载两个人的船,每个人划船渡河的时间不同,当两个人同乘一艘船时,他们划船所用时间按较慢的人
的速度计算。问你n个人全部过河所需的最短时间。要注意的是船划过河对岸再回来的时间也需要计算进去。

解题思路:

  n=1;n=2;n=3的情况很好分析,当n=3时,渡河的时间刚好是三个人所用时间相加,所以我们直接从n=4开始,假设他们按划船的时间从小到大排列是ABCD四人,可以知道,船必须回来才能到达使全部人过去,而回来的人肯定要是已经过河的人中速度最快的那个,这是基于两种策略来的


第一种:AB过去,A回来,CD过去,B回来,AB过去(T=B+A+D+B+B)

第二种:AD过去,A回来,AC过去,A回来,AB过去(T=D+A+C+A+B

我当时找不到该怎么样判断到底选择哪种方案的方法,所以将两种方案全都列了出来,选择耗时最短的那一个。

上代码:

 1 #include<stdio.h>
 2 #include<algorithm>
 3 using namespace std;
 4 int main()
 5 {
 6     int i,j,t,n,ans,k1,k2,min;
 7     int a[1010];
 8     scanf("%d",&t);
 9     while(t--)
10     {
11         scanf("%d",&n);
12         for(i=0; i<n; i++)
13         {
14             scanf("%d",&a[i]);
15         }
16         sort(a,a+n);
17         ans=0;
18         while(n)
19         {
20             if(n==1)
21             {
22                 ans=ans+a[0];
23                 n--;
24             }
25             else if(n==2)
26             {
27                 ans=ans+a[1];
28                 n=n-2;
29             }
30             else if(n==3)
31             {
32                 ans=ans+a[0]+a[1]+a[2];
33                 n=n-3;
34             }
35             else
36             {
37                 k1=2*a[1]+a[0]+a[n-1];
38                 k2=2*a[0]+a[n-1]+a[n-2];
39                 if(k1<k2)
40                 {
41                     min=k1;
42                 }
43                 else
44                 {
45                     min=k2;
46                 }
47                 ans=ans+min;
48                 n=n-2;
49             }
50         }
51         printf("%d
",ans);
52     }
53     return 0;
54 }

 

原文地址:https://www.cnblogs.com/wkfvawl/p/8910621.html