题解 | #搬水果#优先队列解法

搬水果

https://www.nowcoder.com/practice/e4c775b0f3ee42a4bb72c26d2e1eef8a

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    while(cin>>n){
        if(n==0)return 0;
        priority_queue<int,vector<int>,greater<int>>q;
        while(n--){
            int temp;cin>>temp;
            q.push(temp);
        }
        int res=0;
        while(q.size()!=1){
            int t1 = q.top();q.pop();
            int t2 = q.top();q.pop();
            res+=t1+t2;
            q.push(t1+t2);
        }
        cout<<res<<endl;
    }
}
// 64 位输出请用 printf("%lld")

本题实质上是构造哈夫曼树。

c++提供了优先队列priority_queue。默认自动把元素排成从大到小。

要让他从小到大,需要priority_queue<int, vector<int>, greater<int>>q。

这样创建的q就是默认从小到大排序

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:20
点赞 评论 收藏
分享
小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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