题解 | 哈夫曼树

哈夫曼树

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

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

int main() {
    int n;
    while (cin >> n) {
        int ans = 0;
        priority_queue<int, vector<int>, greater<int>> pq;
        while (n--) {
            int x;
            cin >> x;
            pq.push(x);
        }
        while (pq.size() > 1) {
            int a = pq.top();
            pq.pop();
            int b = pq.top();
            pq.pop();
            int x = a + b;
            ans += x;
            pq.push(x);
        }
        cout << ans << endl;
    }
    return 0;
}

全部评论

相关推荐

七牛云头号黑子:人家是过度包装被看出来没过简历,你是包都不包啊兄弟
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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