题目描述: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[]; //store time of people
int main(){
int T;
scanf("%d",&T);
while(T--){
int N;
scanf("%d",&N);
memset(pt,,sizeof(pt));
for(int i=;i<N;i++){
scanf("%d",pt+i);
}
sort(pt,pt+N);
int t=;
while(N>){
if(*pt[]+pt[]>*pt[]+pt[N-]){
t+=*pt[]+pt[N-]+pt[N-];
}
else{
t+=*pt[]+pt[N-]+pt[];
}
N-=;
}
if(N==){
t+=pt[]+pt[]+pt[];
}
else if(N==){
t+=pt[];
}
else{
t+=pt[];
}
printf("%d\n",t);
}
return ;
}