Crossing River(信息学奥赛一本通 - T1232)

题目描述
几个人过河,每次过两人一人回,速度由慢者决定,问过河所需最短时间。

输入格式
输入 t 组数据,
每组数据第 1 行输入n,
第 2 行输入 n 个数,表示每个人过河的时间。

输出格式
输出 t 行数据,每行 1 个数,表示每组过河最少时间。

输入样例
1
4
1 2 5 10

输出样例
17


题解
贪心:

一、当人数 ≤ 3 时

  1. 只有 1 个人:过河时间为 a[1]
  2. 只有 2 个人:过河时间为 a[2]
  3. 只有 3 个人:过河时间为 a[1] + a[2] + a[3]

二、当人数 > 3 时:每次让最慢的两个人过河,有两种过河方案;

  1. 假设过河最快的为 a,次快的为 b,次慢的为 c,最慢的为 d;
  2. a 带 c,a 回来;a 带 d,a 回来;此方案的过河时间为 c + a + d + a,即 2a + c + d
  3. a 带 b,a 回来;c 带 d,b 回来;此方案的过河时间为 b + a + d + b,即 2b + a + d
  4. 每次对两种过河方案取最小值;
#include <iostream>
#include <algorithm>
using namespace std;

int n, T;
int a[1010];

int main()
{
    
    
	cin >> T;
	
	while(T --)
	{
    
    
		cin >> n;
		for (int i = 1; i <= n; i ++) cin >> a[i];
		
		sort(a + 1, a + 1 + n);
		
		int ans = 0;
		while(n > 3)
		{
    
    
			int sum1 = a[1] * 2 + a[n] + a[n - 1];
			int sum2 = a[2] * 2 + a[1] + a[n];
			ans += min(sum1, sum2);
			n -= 2;
		}
		
		if(n == 1) ans += a[1];
		else if(n == 2) ans += a[2];
		else ans += a[1] + a[2] + a[3];
		
		cout << ans << endl;
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46239370/article/details/113846806
今日推荐