Crossing River (Informatics Olympiad One Pass-T1232)

Topic description
Several people cross the river, two people each time, the speed is determined by the slower, ask the shortest time required to cross the river.

Input format
Enter t groups of data,
enter n in the
first row of each group of data, and enter n numbers in the second row, representing the time it takes for each person to cross the river.

Output format
Output t rows of data, 1 number per row, representing the minimum time for each group to cross the river.

Input example
1
4
1 2 5 10

Sample output
17


Problem solution
Greedy:

一、当人数 ≤ 3 时

  1. 只有 1 个人:The time to cross the river is a[1];
  2. 只有 2 个人:The time to cross the river is a[2];
  3. 只有 3 个人:The time to cross the river is a[1] + a[2] + a[3];

二、当人数 > 3 时: Every time the two slowest people cross the river, there are two ways to cross the river;

  1. Suppose that the fastest crossing the river is a, the next fastest is b, the next slowest is c, and the slowest is d;
  2. a 带 c,a 回来;a 带 d,a 回来; The crossing time of this program is c + a + d + a, namely 2a + c + d;
  3. a 带 b,a 回来;c 带 d,b 回来; The crossing time of this program is b + a + d + b, namely 2b + a + d;
  4. Take the minimum value for the two river crossing schemes each time;
#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;
}

Guess you like

Origin blog.csdn.net/weixin_46239370/article/details/113846806