Crossing River poj1700贪心

题目描述:N个人过河,只有一只船,最多只能有两人划船,每个人划船速度不同,船速为最慢的人的速度。输入T为case个数,每个case输入N为人数,接下来一行输入的是每个人过河的时间,都不相同。要求输出N个人全部过河的时间

算法思想:采用贪心的方法。有两种划船的方法,一种是最快+最慢,最快回,最快+次慢,最快回,循环下去;第二种是最快+次快,次快回,最慢+次慢,最快回,循环下去。那么当剩余人数N>3的时候,比较第一种和第二种的时间,采用耗时短的方法过河。N=1,2,3的时候单独讨论。

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int pt[1010];  //store time of people
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        int N;
        scanf("%d",&N);
        memset(pt,0,sizeof(pt));
        for(int i=0;i<N;i++){
            scanf("%d",pt+i);
        }
        sort(pt,pt+N);
        int t=0;
        while(N>3){
            if(2*pt[1]+pt[0]>2*pt[0]+pt[N-2]){
                t+=2*pt[0]+pt[N-1]+pt[N-2];
            }
            else{
                t+=2*pt[1]+pt[N-1]+pt[0];
            }
            N-=2;
        }
        if(N==3){
            t+=pt[2]+pt[0]+pt[1];
        }
        else if(N==2){
            t+=pt[1];
        }
        else{
            t+=pt[0];
        }
        printf("%d
",t);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jxzheng/p/4432408.html