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 each case contains N, and the second line contains N integers giving the time for each people to cross the river. 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
4
1 2 5 10
Sample Output
17
n个人过河,最多一次过去两个人,只有一艘船,所以还得回来。也是贪心,关键在于四个人的时候有两种不同情况,需要讨论是那种情况。
题目给的用例就是1 2先过去,1回来,5 10过去 2回来,12过去。答案是17
还有一种可能比如1 100 100 100
就是让1来回跑:1 100 过去,1回来,1 100 过去,1回来,1 100 过去,答案是 302
而大于四个人的情况可以看成每次的目的是把最慢的两个人运过去,自己理解吧,懒得写了。
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
int main()
{
int i, j, m, n, k, a[1000];
while (~scanf("%d", &n))
{
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
qsort(a, n,sizeof(a[0]),cmp);
m = 0;
int c = 0, b = 0;
if (n < 3)
m = a[n - 1];
else if (n == 3)
m = a[0] + a[1] + a[2];
else
{
for (i = n - 1, k = 0; i > 2; i -= 2, k++)
{
c += a[i] + 2 * a[1] + a[0];
b += a[i] + a[i - 1] + 2 * a[0];
if (b > c)
b = c;
else
c = b;
}
if (n % 2 == 0)
c += a[1];
else
c += a[0] + a[1] + a[2];
m = c;
}
printf("%d\n", m);
}
return 0;
}