北京邮电大学 哈夫曼树

#include<bits/stdc++.h>
#include<queue>
using namespace std;
int main(){
    int n,x;
    priority_queue<int,vector<int>,greater<int> >q;
    while(scanf("%d",&n)!=EOF){
        for(int i=0;i<n;i++){
            scanf("%d",&x);
            q.push(x);  
        }
        int ans=0;
        while(q.size()>1){
            int x1=q.top();
            q.pop();
            int x2=q.top();
            q.pop();
            ans+=(x1+x2);
            q.push(x1+x2);
        }
        printf("%d\n",ans); 
    }
    return 0;   
}

猜你喜欢

转载自blog.csdn.net/qq_31674679/article/details/80203676