POJ 1700 Crossing River 【经典贪心】

Crossing River

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 16936 Accepted: 6407

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

Source

POJ Monthly–2004.07.18

题意: n个人过河,但是只有一条船,限载两人,每个人都有一个过河时间,在一条船上过河时间为二人较慢的,问你最短的过河时间使得所有人到河对岸

分析: 时隔好长时间再次做到这个题,刚开始还有点思维定式,后来好多了,策略如下,排序后,如果只有1,2,3人,这里省略,如果大于四人,我们假设最快的为a,次快的为b,最慢的为d,次最慢的为c,这里我们有两个小策略使得把c,d送到对岸,我们可以让a,d在一条船上,然后a回,再送c,a回,这样耗时为 c+d+2*a,也可以先把a,b送到对面,然后a回,然后c,d去,b回,这样耗时为 a+d+2*b,我们就可以贪心的来比较即可

参考代码

#include 
#include 
#include 
using namespace std;

const int N = 1e5 + 10;

int A[N];

int main(){
    ios_base::sync_with_stdio(0);
    int T;cin>>T;
    while (T--) {
        int n;cin>>n;
        for(int i = 0;i < n;i++) {
            cin>>A[i];
        }
        sort(A,A+n);
        int sum = 0;
        int a = A[0];
        int b = A[1];
        int p = n-1;
        for(;p >= 3;p-=2) {
            int c = A[p-1];
            int d = A[p];
            if(a+c > 2*b) {
                sum += d+a+2*b;
            } else {
                sum += c+d+2*a;
            }
        }
        if(p == 2) {
            sum += A[p] + b+ a;
        } else if (p == 1){
            sum += b;
        } else if(p == 0) {
            sum += a;
        }
        cout<return 0;
}
  • 如有错误或遗漏,请私聊下UP,thx

你可能感兴趣的:(----,贪心----)