CF884D:Boxes And Balls

浅谈\(Huffman\)树:https://www.cnblogs.com/AKMer/p/10300870.html

题目传送门:https://codeforces.com/problemset/problem/884/D

把分离倒过来就是合并,每次尽量多合并可以保证答案更优,所以问题就转化成了裸的\(3\)\(Huffman\)树问题。

时间复杂度:\(O(nlogn)\)

空间复杂度:\(O(n)\)

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;

const int maxn=2e5+5;

int n;
ll ans;

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

struct Heap {
	int tot;
	ll tree[maxn];

	void ins(ll v) {
		tree[++tot]=v;
		int pos=tot;
		while(pos>1) {
			if(tree[pos]<tree[pos>>1])
				swap(tree[pos],tree[pos>>1]),pos>>=1;
			else break;
		}
	}

	ll pop() {
		ll res=tree[1];
		tree[1]=tree[tot--];
		int pos=1,son=2;
		while(son<=tot) {
			if(son<tot&&tree[son|1]<tree[son])son|=1;
			if(tree[son]<tree[pos])
				swap(tree[son],tree[pos]),pos=son,son=pos<<1;
			else break;
		}
		return res;
	}
}T;

int main() {
	n=read();
	if(n%2==0)T.ins(0);
	for(int i=1;i<=n;i++) {
		int x=read();
		T.ins(x);
	}
	while(T.tot!=1) {
		ll a=T.pop(),b=T.pop(),c=T.pop();
		a+=b+c,T.ins(a),ans+=a;
	}
	printf("%I64d\n",ans);
	return 0;
}
posted @ 2019-01-23 16:57  AKMer  阅读(277)  评论(0编辑  收藏  举报