Crossing River 贪心

传送门

参考博客

参考博客

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

题解:

题意概括:有n个人想要渡河,但是只有一条船,仅能容纳两个人,每个人的渡河速度不同,两个人乘坐时速度为最慢的那一个。问这n个人通过这条河的最快速度是多少。

这是典型的贪心问题。

如果只有1个或两个人的话,直接过即可。

如果有3个人,速度a<b<c,则渡河速度为c+a。

如果有四个人或者四个人以上,把用时最少的a、用时次少的b、用时次长的c、用时最长的d看成一个组合,借a、b送走c、d(但是a、b还要回到原来的地方),此时a、b依然没有过河,于是又可以和其他的人组成像上面的组合,重复这个操作。

当a、b要送c、d到对岸的时候,有两种方法。

1、a、b过去,a回来,c、d过去,b回来。(b+a+d+b)

2、a、c过去,a回来,a、d过去,a回来。(c+a+d+a)

选择(b+a+d+b)和(c+a+d+a)中时间最短的加到总时间上。

//#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <map>

using namespace std;

const int maxn=1e3+10;

int a[maxn];

int main()
{
//	freopen("input.txt","r",stdin);
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
		}
		sort(a,a+n);
		int time=0;
		for(int i=n-1;i>=0;i-=2)
		{
			if(i+1==1) 
			{
				time+=a[i];
				cout<<time<<endl;
//				cout<<time;
				break;
			}
			else if(i+1==2)
			{
				time+=a[1];
				cout<<time<<endl;
				break;
			}
			else if(i+1==3)
			{
				time+=(a[2]+a[0]+a[1]);
				cout<<time<<endl;
				break;
			}
			else if(i+1>=4)
			{
				time+=min(2*a[1]+a[0]+a[i],2*a[0]+a[i-1]+a[i]);
			}
		}
	}
	
	
	return 0;
}
原创文章 99 获赞 15 访问量 7354

猜你喜欢

转载自blog.csdn.net/qq_45328552/article/details/101457333