CodeForces 884D---Boxes And Balls(哈夫曼树)

传送门:https://codeforces.com/problemset/problem/884/D
Description
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 a 1, a 2, …, a n (1 ≤ a i ≤ 109), where a i is the number of balls with color i.

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

Input
3
1 2 3

Output
6

Input
4
2 3 4 5

Output
19

思路:
先把大的分出去,惩罚的更少,到底是分2个还是分3个怎么选择,分3个的情况当然是最佳的,那么什么时候分两个,怎么分?当n是偶数的时候,加入一个0,然后就能一直分3个。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <string>
#include <sstream>
#include <stack>
#include <queue>
#include <map>

using namespace std;
const int inf=0x3f3f3f3f;
const int MAX=2e5+5;
int n,sum;
long long wpl;
int num;
priority_queue<long long,vector<long long>,greater<long long> >q;
bool cmp(int a,int b){
	return a>b;
}
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>num;
		q.push(num);
	}
	if(!(n&1))	q.push(0);
	while(q.size()>1){
		long long  min1=q.top();q.pop();
		long long  min2=q.top();q.pop();
		long long  min3=q.top();q.pop();
		q.push(min1+min2+min3);
		wpl+=min1+min2+min3;
	}
	cout<<wpl<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值