题目一:有A组人,每组有N人,想用一艘船渡河,该船一次只能载两个人。每个人划船的速度不同,当两个人一组时船的速度由最慢的人决定。求一种方法能让所有人过河并且船的往返时间最短。
输入:第一行输入A;第二行输入N(不超过1000);第三行输入速度(不超过100);
输出:往返时间
样例:
输入
1
4
1 2 5 10
输出
17
#include <stdio.h>
#include <stdlib.h>
int Partition(int speed[],int low,int high){
speed[0]=speed[low];
int pivotkey=speed[low];
while(low<high){
while(low<high&&speed[high]>=pivotkey) high--;
speed[low]=speed[high];
while(low<high&&speed[low]<=pivotkey) low++;
speed[high]=speed[low];
}
speed[low]=speed[0];
return low;
}
void Qsort(int speed[],int low,int high){
if(low<high){
int pivotloc=Partition(speed,low,high);
Qsort(speed,low,pivotloc-1);
Qsort(speed,pivotloc+1,high);
}
}
int main(){
int A,N,time=0;
scanf("%d",&A);
for(int i=0;i<A;i++){
scanf("%d",&N);
int *speed=(int*)malloc((N+1)*sizeof(int));
for(int j=1;j<=N;j++){
scanf("%d",&speed[j]);
}
Qsort(speed,1,N);
while (N > 0) {
if (N== 1) {
time += speed[1];
break;
}
else if (N == 2) {
time += speed[2];
break;
}
else if (N == 3) {
time += speed[1] + speed[2] + speed[3];
break;
}
else {
int s1, s2;
s1 = speed[N] + speed[1] + speed[N - 1] + speed[1];
s2 = speed[2] + speed[1] + speed[N] + speed[2];
time += s1>s2?s2:s1;
N -= 2;
}
}
printf("%d\n",time);
}
return 0;
}