POJ 2573 Bridge 贪心

Description

n people wish to cross a bridge at night. A group of at most two people may cross at any time, and each group must have a flashlight. Only one flashlight is available among the n people, so some sort of shuttle arrangement must be arranged in order to return the flashlight so that more people may cross.
Each person has a different crossing speed; the speed of a group is determined by the speed of the slower member. Your job is to determine a strategy that gets all n people across the bridge in the minimum time.

Input
The first line of input contains n, followed by n lines giving the crossing times for each of the people. There are not more than 1000 people and nobody takes more than 100 seconds to cross the bridge.

Output
The first line of output must contain the total number of seconds required for all n people to cross the bridge. The following lines give a strategy for achieving this time. Each line contains either one or two integers, indicating which person or people form the next group to cross. (Each person is indicated by the crossing time specified in the input. Although many people may have the same crossing time the ambiguity is of no consequence.) Note that the crossings alternate directions, as it is necessary to return the flashlight so that more may cross. If more than one strategy yields the minimal time, any one will do.

Sample Input
4
1
2
5
10

Sample Output
17
1 2
1
5 10
2
1 2

题意:有n个人想过桥,每个人速度为ai,现在过桥可以一个人或两个人过桥,只有一盏灯,要有灯才能过桥,如果两人一起过,速度取决于慢的那个人的速度,问最快时间和过桥方法。

分析:显然每次过两人才能使桥的利用最大化,且送灯的时间应该尽量少,问题的关键在于过桥的时间取决于慢的那个人。
三个人的策略:最快的a1和一个人先过桥,然后a1回来接另一个,总时间就是a1+a2+a3.
四个人的策略,首先假设a数组升序。

  • 第一种:a1送最慢的an过去,a1再回来;然后a1再送an-1过去,a1回去。
    所以总时间是2a1+an-1+an.
  • 第二种:a1和a2先过去(因为a2的过桥时间短,所以这次过桥对答案贡献很大),然后an-1和an一起过。a1和a2分别回去送灯。
    这样的总时间就是2*a2+a1+an.

经过这样的分析,发现利用最快的a1和a2,每次可以将两名速度慢的同学送过桥,如果最后剩下的是一个人,那就当成三人过桥处理即可。

Solution

#include<cstdio>
#include<iostream>
#include<algorithm>
#define N 1010
using namespace std;
int a[N],n;
inline void init(){
	scanf("%d",&n);
	for (int i = 1;i <= n; i++) scanf("%d",&a[i]);
	sort(a + 1,a + 1 + n);
}
void print(){
	//打印方法
	for (int i = n-2;i >= 2; i-=2)
	{
		if (a[1] + a[2]*2 + a[i+2] < a[1]*2 + a[i+1] + a[i+2]) 
			printf("%d %d\n%d\n%d %d\n%d\n",a[1],a[2],a[1],a[i+1],a[i+2],a[2]);
                else  printf("%d %d\n%d\n%d %d\n%d\n",a[1],a[i+2],a[1],a[1],a[i+1],a[1]);
	}
	if (n % 2) printf("%d %d\n%d\n",a[1],a[3],a[1]);
    printf("%d %d\n",a[1],a[2]);
} 
void solve(){
	//总时间
	if (n == 1) 
	{
		printf("%d\n%d\n", a[1],a[1]);
		return;
	}
	if (n == 2) 
	{
		printf("%d\n%d %d\n", a[2],a[1],a[2]);
		return;
	}
	int ans = a[2];
	for (int i = n-2;i >= 2; i-=2)
		ans += min(a[1] + a[2]*2 + a[i+2], a[1]*2 + a[i+1] + a[i+2]);
	if (n % 2) ans += a[1]+a[3];
	printf("%d\n", ans);
	print();
}
int main(){
	init();
	solve();
	return 0;
} 
posted @ 2019-02-12 15:32  Mr.doublerun  阅读(22)  评论(0)    收藏  举报