5.codeup-哈夫曼树-问题 C: 哈夫曼树

54 阅读1分钟

思路

  • 同合并果子

注意

  • 可以使用优先队列

代码

#include<queue>
using namespace std;
int n;

priority_queue<int,vector<int>,greater<int> > q;
int main(){
	while(scanf("%d",&n)!=EOF){
		while(!q.empty()) q.pop();
		int x;
		for(int i=0;i<n;i++){
			scanf("%d",&x);
			q.push(x);
		}
		int ans=0;
		while(q.size()>1){
			int a=q.top();
			q.pop();
			int b=q.top();
			q.pop();
			q.push(a+b);
			ans+=a+b;
		}
		printf("%d\n",ans);
	}
	return 0;
}