NYOJ 47 过河问题&&POJ 1700 Crossing River

/*
题目大意:求解最小的过桥时间
解题思路:

假设m个排序的过桥时间:a0,a1,a2,a3,a4......am-1
已知条件:最后一步肯定是a0和a1一起过去,所以所花的时间初始化sum=a[1]

过河两种方法,每次过两个人(所以需要m-=2):
1.a0和a1过去,a0回来,am-2和am-1过去,a1回来,所花时间sum+=a[1]+a[0]+a[m-1]+a[1]
2.a0和am-1过去,a0回来和am-2过去,a0再回来,所花时间sum+=a[m-1]+a[0]+a[m-2]+a[0]

最后只有2种情况:如果m为奇数则剩3个人,如果m为偶数则剩2个人
由于前面初始化sum=a[1],所以只需考虑3个人时a0将a2送过去再回来的所花的额外时间sum+=a[2]+a[0]


难点详解:注意一下过桥的方法就可以了,还要考虑一下最后剩下几个人。
关键点:贪心算法
解题人:lingnichong
解题时间:2014-08-23 21:06:46
解题体会:感觉题目没意思,虽说它是一道经典的贪心题目,如果有1000个人过河,每个人过100秒,那不就是100000秒吗?这手电筒的电池也太强大了吧!这夜晚也太长了吧!偷笑
*/


过河问题

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 5
描述

在漆黑的夜里,N位旅行者来到了一座狭窄而且没有护栏的桥边。如果不借助手电筒的话,大家是无论如何也不敢过桥去的。不幸的是,N个人一共只带了一只手电筒,而桥窄得只够让两个人同时过。如果各自单独过桥的话,N人所需要的时间已知;而如果两人同时过桥,所需要的时间就是走得比较慢的那个人单独行动时所需的时间。问题是,如何设计一个方案,让这N人尽快过桥。 

输入
第一行是一个整数T(1<=T<=20)表示测试数据的组数
每组测试数据的第一行是一个整数N(1<=N<=1000)表示共有N个人要过河
每组测试数据的第二行是N个整数Si,表示此人过河所需要花时间。(0<Si<=100)
输出
输出所有人都过河需要用的最少时间
样例输入
1
4
1 2 5 10
样例输出
17
来源
POJ
上传者
张云聪

poj题目:


Crossing River
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 10871 Accepted: 4097

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 the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. 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. Each case is preceded by a blank line. 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

1
4
1 2 5 10

Sample Output

17

Source



#include<stdio.h>
#include<algorithm>
using namespace std;
#define MAXN 1000+10
int arr[MAXN];
int main()
{
	int t,n;
	int i,time;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(i=0;i<n;i++)
			scanf("%d",&arr[i]);
		sort(arr,arr+n);
		if(n<=2)
		{
			printf("%d\n",arr[n-1]);
			continue;
		}
		time=arr[1];
		while(n>3)
		{
			if(arr[1]+arr[0]+arr[n-1]+arr[1]>arr[n-1]+arr[0]+arr[n-2]+arr[0])
				time += arr[n-1]+arr[0]+arr[n-2]+arr[0];
			else
				time += arr[1]+arr[0]+arr[n-1]+arr[1];
			n -= 2;
		}
		if(n==3)
			time += arr[2] + arr[0];
		printf("%d\n",time);
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值