poj 1700 Crossing River 【贪心】

Crossing River

Time Limit: 1000MS

 

Memory Limit: 10000K
Total Submissions: 11557   Accepted: 4368

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
我们假设0是最快的,1是第二快的人,n-1是最慢的人,n-2是第二慢的人。 
那我们需要借助0,1把n-1,n-2送过去。 方案有二
一:先过去两个最快的0,1,再让0回去,然后让两个用时最长的n-1,n-2一起过去,最后剩余的1回去。 用时 T1 + T0 + Tn-2 +T1.
二:让0,n-2先过去,0回来,然后0和n-1过去,0再回来。 用时 Tn-2 + T0 + Tn-1 + T0.
特别的  当人数为2人时,最优时间 是两个人中过河最慢的人所耗费的时间;而人数为3时,最优时间是3人过河时间之和。
#include <cstdio>
#include <cstring>
#include <algorithm> 
#define MAX 1000+10
using namespace std;
int man[MAX];
int n;
void input()
{
    for(int i = 0; i < n; i++)
    scanf("%d", &man[i]);
}
void slove()
{
    int time = 0; 
    sort(man, man+n);//升序排列 </span>
    if(n <= 2)//这里没加 错了一次。。。
    {
        printf("%d\n", man[n-1]);
        return ;
    } 
    while(n > 3)
    {
        time +=  min(2*man[0]+man[n-1]+man[n-2], man[0]+2*man[1]+man[n-1]);
        n -= 2;
    }
    if(n == 3)
    printf("%d\n", time+man[0]+man[1]+man[2]);
    else
    printf("%d\n", time+man[1]);
}
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        input();
        slove();
    }
    return 0;
}


你可能感兴趣的:(poj 1700 Crossing River 【贪心】)