题意是N个人过河,船每次只能坐两个人,船载每个人过河的所需时间不同,问最快的过河时间。
解题思路:当n=1,2,3时所需要的最小时间很容易求得,现在由n>=4,假设n个人单独过河所需要的时间存储在数组t中,将数组t按升序排序,那么 这时将单独过河所需要时间最多的两个旅行者送到对岸去,有两种方式:
1> 最快的(即所用时间a[0])和次快的过河,然后最快的将船划回来,再次慢的和最慢的过河,然后次快的将船划回来.
即所需时间为:a[0]+2*a[1]+a[n-1]
2> 最快的和最慢的过河,然后最快的将船划回来,再最快的和次慢的过河,然后最快的将船划回来.
即所需时间为:2*a[0]+a[n-2]+a[n-1]
这样就将过河所需时间最大的两个人送过了河,而对于剩下的人,采用同样的处理方式,接下来做的就是判断怎样用的时间最少.
代码::
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main()
{
int t,n,a[1001],i,sum;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
sum=0;
for(i=0; i<n; i++)
scanf("%d",&a[i]);
sort(a,a+n);
for(i=n-1; i>2; i-=2)
if(a[0]+2*a[1]+a[i]>2*a[0]+a[i-1]+a[i])
sum+=2*a[0]+a[i-1]+a[i];
else
sum+=a[0]+2*a[1]+a[i];
if(i==2)
sum+=a[0]+a[1]+a[2];
else if(i==1)
sum+=a[1];
else
sum+=a[0];
printf("%d\n",sum);
}
return 0;
}