搬水果——吉林大学复试上机

解题思路:纯粹的哈夫曼树模板,注意一下边界就行。

#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;
} 
全部评论

相关推荐

06-26 17:24
已编辑
宁波大学 golang
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-15 17:32
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务