1. 程式人生 > >Crossing River (PKU 1700)——貪心法

Crossing River (PKU 1700)——貪心法

Crossing River
Time Limit: 1000MSMemory Limit: 10000K
Total Submissions: 19150Accepted: 7139

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

Answer

#include <cstdio>
int MIN_(int a, int b){
    if(a>b) return b;
    else return a;
}
int main(){
    int t, n, tmp, speed[1005];
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        for(int i=0; i<n; i++){
            scanf("%d", &speed[i]);
        }
        // bubble sort(0->n:small->large)
        for(int i=0; i<n; i++){
            for(int j=i; j<n; j++){
                if(speed[i] > speed[j]){
                    tmp = speed[i];
                    speed[i] = speed[j];
                    speed[j] = tmp;
                }
            }
        }
        // greedy
        int start = n, ans = 0;
        while(start){
            // start = 1,2,3時直接處理 
            if(start == 1){
                ans  += speed[0];
                break; 
            }
            else if(start == 2){
                ans += speed[1];
                break;
            }
            else if(start == 3){ // 0,2過河,0回程,0,1過河 
                ans += speed[2]+speed[0]+speed[1];
                break;
            } 
            else{
                ans += MIN_(speed[1]+speed[0]+speed[start-1]+speed[1], speed[start-1]+2*speed[0]+speed[start-2]);
                start -= 2; 
            } 
        } 
        printf("%d\n", ans);
    }    
    return 0;
}