POJ 1700----Crossing River(过桥问题)

来源:互联网 发布:ae2015中文下载mac 编辑:程序博客网 时间:2024/05/01 16:13

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

141 2 5 10

Sample Output

17
#include <stdio.h>  #include <algorithm>      using namespace std;      #define N 1010int a[N];  int main()  {     int T,i,n,s;    scanf("%d", &T);      while(T--)      {          scanf("%d", &n);          for(i=0;i<n;i++)  scanf("%d", &a[i]);          sort(a,a+n);          s=0;          while(n)          {              if(n==1)              {                  s+=a[0];                  break;              }              else if(n==2)              {                  s+=a[1];                  break;              }              else if(n==3)              {                  s+=a[0]+a[1]+a[2];                  break;              }              else              {  //模式1:A将Z送过桥,然后返回,再把Y送过桥,再返回;      //模式2:A和B先过桥,然后A返回,Y和Z过桥,然后B返回                if(2*a[1]>a[0]+a[n-2]) s+=2*a[0]+a[n-1]+a[n-2];  //当2b>a+y时,使用模式一                else s+=a[0]+a[n-1]+a[1]*2;  //使用模式2             }              n-=2;             }   printf("%d\n", s);        } return 0;} 


0 0
原创粉丝点击