Crossing River(贪心)

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值