大健健学长以前讲过的一道非常经典的霍夫曼树求非叶子节点的和的题目。如果把切木板的过程逆着看,就是贪心地构造霍夫曼树的过程,用优先队列维护。
//432K 47MS
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
int main(){
int n;
while(~scanf("%d", &n)){
priority_queue<ll, vector<ll>, greater<ll> > pque;
ll e;
for(int i=0; i<n; i++){
scanf("%d", &e);
pque.push(e);
}
ll res = 0;
while(pque.size() > 1){
ll e1 = pque.top(); pque.pop();
ll e2 = pque.top(); pque.pop();
pque.push(e1+e2);
res += e1+e2;
}
printf("%lld\n", res);
}
return 0;
}