CodeForces - 884D Boxes And Balls

Boxes And Balls

Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:

Ivan chooses any non-empty box and takes all balls from this box;
Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.

The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!

Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, …, an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.

Output
Print one number — the minimum possible penalty of the game.

Examples

Input

3
1 2 3

Output

6

Input

4
2 3 4 5

Output

19

本题题意:有n种球n个盒子,给n个数代表第i种颜色的求有多少个,初始时所有的球都在一个盒子中,现要将第i个颜色的球放入第i个盒子中,每次只能选择一个非空盒子,然后将其中所有球拿出来,然后再选k个空盒子,将所有的球全部任意分配至这k个盒子中,每次消耗拿出球的个数。求最小的消耗。

解题思路:我们可以逆向推,看做将n个数合并,每次都要满足k=3,且每次放入三个最小的,才能满足消耗最小,发现当n为奇数时可以满足,如果n不为奇数则加一个0进去,即可满足,用哈夫曼树求解。

AC代码如下:

#include<iostream>
#include<queue>
#include<functional>
using namespace std;
const int maxn = 2e5 + 5;
long long a[maxn];
typedef long long ll;
int main()
{
	int n;
	/*cin >> n;*/
	scanf("%d", &n);
	priority_queue<ll, vector<ll>, greater<ll>>que;
	
		for (int i = 0; i < n; i++)
		{
			//cin >> a[i];
			scanf("%d", &a[i]);
			que.push(a[i]);
		}
		if (n == 1)
		{
			cout << 0 << endl;

		}
		else{
			if (n % 2 == 0)que.push(0);

			ll ans = 0;
			while (que.size() > 2)
			{
				ll m1 = que.top();
				que.pop();
				ll m2 = que.top();
				que.pop();
				ll m3 = que.top();
				que.pop();
				ans += m1 + m2 + m3;
				que.push(m1 + m2 + m3);
			}

			cout << ans << endl;
		}
	return 0;
}

发布了40 篇原创文章 · 获赞 10 · 访问量 2567

猜你喜欢

转载自blog.csdn.net/lsdstone/article/details/101113851