哈夫曼树概念:
#include<queue>
#include<stdio.h>
using namespace std;
priority_queue<int,vector<int>,greater<int> > Q;
int main(){
int n;
while(scanf("%d",&n)!=EOF){
while(Q.empty()==false) Q.pop();//清空堆中元素
for(int i=1;i<=n;i++){ //输入n个叶子节点权值
int x;
scanf("%d",&x);
Q.push(x); //将权值放入堆中
}
int ans=0; //保存答案
while(Q.size()>1){ //当堆中元素大于1
int a=Q.top();
Q.pop();
int b=Q.top();
Q.pop(); //取出堆中两个最小元素
ans+=a+b;
Q.push(a+b);//将新生成的节点权值放入堆中
}
printf("%d\n",ans);
}
return 0;
}