poj 1700 Crossing River

Crossing River
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 12508   Accepted: 4754

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

POJ Monthly--2004.07.18

题意:木桥上最多能承受两个人同时经过,否则将会坍塌.每个人单独过独木桥都需要一定的时间,不同的人要的时间可能不同.两个人一起过独木桥时,由于只有一盏灯,所以需要的时间是较慢的那个人单独过桥所花费的时间.现在输入N(2<=N<1000)和这N个人单独过桥需要的时间,请计算总共最少需要多少时间,他们才能全部到达河对左岸.

有两种方法:
一、最快和次快过桥,最快返回去;然后最慢和次慢过桥,次快返回去,最快的和次快的过桥,t1=a[1]+a[0]+a[n-1]+a[1]+a[1]。二、最快和最慢过桥,最快返回;最快和次快过去,最快返回,最快的和次慢的过去,t2=a[n-1]+a[0]+a[1]+a[0]+a[n-2]。选择两者中用时较少的一个行,判断t1与t2大小,只需要判断2a[1]是否大于a[0]+a[n-2],这样就将最慢和次慢送过河了,对剩下n-2个人进行循环处理。注意当n=1、n=2、n=3时直接相加就可以了。

AC代码:

#include<iostream>
#include<algorithm>
using namespace std;
int a[1010];
int main()
{
    int T,N;
    int i,min;
    cin>>T;
    while(T--)
    {
        min=0;
        cin>>N;
        for(i=1;i<=N;i++)
        cin>>a[i];
        sort(a,a+N+1);
        while(N)
        {
            if(N==1){
                min+=a[1];break;
            }
            else if(N==2){
            	min+=a[2];break;
			}
            else if(N==3){
                min+=a[1]+a[2]+a[3];
                break;
            }
            else{
                if(2*a[2]>(a[1]+a[N-1]))
                min+=2*a[1]+a[N]+a[N-1];
                else min+=2*a[2]+a[1]+a[N];
                N=N-2;
            }
        }
            cout<<min<<endl;
    }
    return 0;
}


你可能感兴趣的:(poj 1700 Crossing River)