题解 | #搬水果#

搬水果

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

这道题的思路和求哈夫曼树的权值是一样的,哈夫曼树题目链接:https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155?tpId=67&tqId=29635&tPage=1&ru=/kaoyan/retest/1005&qru=/ta/bupt-kaoyan/question-ranking

#include <bits/stdc++.h>
#include <iostream>
#include <queue>
using namespace std;

int main() {
    int n;
    while(cin >> n){
        if(n == 0) break;
        priority_queue<int, vector<int>, greater<int>> datas;
        while(n--){
            int x;
            cin >> x;
            datas.push(x);
        }

        int ans = 0;
        while(datas.size() > 1){
            int a = datas.top();
            datas.pop();
            int b = datas.top();
            datas.pop();
            ans += a + b;
            datas.push(a + b);
        }
        cout << ans << '\n';
        
    }
    
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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