POJ 1700 Crossing River

Crossing River
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 20037   Accepted: 7453

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

题目大意:有N个人要渡河,但是只有一艘船,船上每次最多只能载两个人,渡河的速度由两个人中较慢的那个决定,小船来回载人直到所有人都渡河,求最短的渡河时间。

分析:渡河速度由较慢的决定,而且还必须要有一个人把小船撑回起点,这题最关键的思路就是一直用两个最快的人依次帮助最慢的两个人过河,假设有速度最快的人a、速度次快的人b,速度最慢的人c,速度次慢的人d,把c和d送到终点考虑两种策略

▶1、 a和b出发,a回来,c和d出发,b回来  time = b + a + d + b

▶2、 a和c出发,a回来,a和d出发,a回来  time = c + a + d + a

那么需要考虑2 * b和c + a的大小关系,选择用时更短的方案即可

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define N 1000 + 5
int a[N];
int main() {        
    int t;
    scanf("%d", &t);
    while(t--) {
        int n;      
        scanf("%d", &n);
        for(int i = 0; i < n; i++) scanf("%d", &a[i]);
        sort(a, a+n);
        int time = 0;
        while(1) {
            if(n == 1) {
                time += a[0];
                break;
            } else if(n == 2) {
                time += a[1];
                break;
            } else if(n == 3) {
                time += a[0] + a[1] + a[2];
                break;
            }
            if(2*a[1] <= a[n-2]+a[0]) time += 2*a[1] + a[0] + a[n-1];
            else time += 2*a[0] + a[n-2] + a[n-1];
            n -= 2;
        }
        printf("%d\n", time); 
    }
    return 0;
}

 

posted on 2018-08-05 09:49  kindleheart  阅读(150)  评论(0编辑  收藏  举报