BIT2014级软件学院程序设计-07 Crossing River

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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值