解题思路:纯粹的哈夫曼树模板,注意一下边界就行。
#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;
}