题解 | #哈夫曼树#

哈夫曼树

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

需要把所有元素值的负数存入优先队列,然后每次top出2个最大的,也就是原叶子结点中2个权值最小的。

top完别忘pop,再把新节点push进优先队列,用wpl累加,最后输入wpl时别忘再乘回来-1

#include <iostream>
#include <cstdio>
#include <queue>

using namespace std;


int main() {
    int n;
    while (scanf("%d", &n) != EOF) {
        priority_queue<int> myPriorityQueue;
        int wpl = 0;
        for (int i = 0; i < n; i++) {
            int num;
            cin >> num;
            //乘-1再入优先队列,即可巧妙运用默认的大根堆实现小根堆
            myPriorityQueue.push(num * (-1));
        }

        //wpl不断累加,退出条件是优先队列中只有一个根节点
        while (myPriorityQueue.size() > 1) {
            int small1 = myPriorityQueue.top();
            myPriorityQueue.pop();
            int small2 = myPriorityQueue.top();
            myPriorityQueue.pop();
            int newWeight = small1 + small2;
            myPriorityQueue.push(newWeight);//别忘新节点入队

            wpl = wpl + small1 + small2;
        }
        printf("%d\n",wpl*(-1));
    }
}
全部评论

相关推荐

嵌入式求职之路:可以看我经验😂,https://www.nowcoder.com/share/jump/73221730841876945
点赞 评论 收藏
分享
04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
今天 11:16
湖南大学 Web前端
我看到好多人都在说0offer好焦虑,结果一看是投了百度快手字节啥的。好像大家都是只想通过校招进大厂,对小公司是不考虑的吗😂可是能进大厂的难道不是只有少部分人吗,真心发问
梦想是成为七海千秋:沉默的大多数吧,喜欢晒的都是能引起共鸣的大厂,找小厂的人,别人也不认识你这个小厂,就自己偷偷找了实际上大多数人哪有什么机会能找到大厂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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