当前位置: 首页 > 工具软件 > River Trail > 使用案例 >

Crossing River(贪心)

司马渝
2023-12-01

poj1700

题目:

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个人要过河,只有1条船,船每次最多乘2人,每个人的过河时间不同,两人一起过河取时间慢的为该次的过河时间。

需注意,过河后需要有人把船再划回来以便下一波的人过河,

需考虑尽量让返程的人速度最快,便可节省时间,所以每次可以借助速度最快的前两个过河!

假设a<b<c<d,此为时间的大小

有两种方法:

第一种:a,b过河,a回来,c,d过河, b回来(此时起点岸又剩下a,b两个了,循环协助其他人过河!!)

第二种:a,c过河,a回来,a,d过河,a回来

选择时间少的!

例:1,2,5,10

一:(1,2)过河,1回来,(5,10)过河,2回来,(1,2)过河,完成!!需要2+1+10+2+1=17

二:(1,5)过河,1回来,(1,10)过河,1回来,(1,2)过河,完成!!需要5+1+10+1+2=18

 

当人数小于4时,直接可以列举。。

#include <cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
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]);
        }
        sort(speed,speed+n);
        int start = n, ans = 0;
        while(start){
            if(start == 1){
                ans  += speed[0];
                break;
            }
            else if(start == 2){
                ans += speed[1];
                break;
            }
            else if(start == 3){
                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;
}

 

 类似资料: