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

搬水果

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就是默认从小到大排序

全部评论

相关推荐

勤劳的鲸鱼在okr拆解:没有别的选择就去吧,有实习和没实习找工作是天上地下
点赞 评论 收藏
分享
想申请延毕了,找工作找到崩溃,越找就越想摆烂,还有25届的和我一样感受吗?
码农索隆:没事哒,好兄弟,慢慢来,调整心态,车到山前必有路,感到迷茫的时候,多抬头看看
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务