牛客网题目链接
模板题
哈夫曼树
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
int main(){
int n;
priority_queue<int,vector<int>,greater<int> > q;
while(scanf("%d",&n) != EOF&&n!=0){
while(!q.empty()){
q.pop();
}
int x,y,ans = 0,tmp;
for(int i = 0;i < n;i++){
scanf("%d",&tmp);
q.push(tmp);
}
while(q.size() > 1) { //保证至少有两个元素在队列中
x = q.top();
q.pop();
y=q.top();
q.pop();
ans+=x+y;
q.push(x+y);
} if(n==1) {
printf("%d\n",tmp);
continue;
}
printf("%d\n",ans);
}
return 0;
}