题解 | 哈夫曼树

哈夫曼树

https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155

#include <stdio.h>
#include <string>
#include <queue>
using namespace std;
int main() {
    priority_queue<int> pqueue;//存储权值的相反数
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        int leaf;
        scanf("%d", &leaf);
        pqueue.push(-1*leaf);
    }
    int weight = 0;
    while (pqueue.size() >= 2) {
        int leaf1 = pqueue.top();
        pqueue.pop();
        int leaf2 = pqueue.top();
        pqueue.pop();
        weight += leaf1 + leaf2;
        pqueue.push(leaf1 + leaf2);
    }printf("%d\n", -1 * weight);

        return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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