题解 | #哈夫曼树#

哈夫曼树

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

带权路径长度即是叶节点权值与路径长度乘积的和,也是所有非叶节点权值的和

#include <iostream>
#include <queue>
using namespace std;

int main() {
    int n;
    while (cin >> n) { // 注意 while 处理多个 case
        // cout << a + b << endl;
        priority_queue<int,vector<int>,greater<int>> myQueue;
        while(n--){
            int temp;
            cin>>temp;
            myQueue.push(temp);
        }
        int sum=0;
        while(myQueue.size()>1){
            int a=myQueue.top();
            myQueue.pop();
            a+=myQueue.top();
            myQueue.pop();
            myQueue.push(a);
            sum+=a;
        }
        // sum+=myQueue.top();
        cout<<sum<<endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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