题解 | #哈夫曼树#
哈夫曼树
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")

查看1道真题和解析