题目描述
给出一组数字,求使用这组数字构造的哈夫曼树的带权路径长度。
输入样例
6
45 12 14 16 5 8
输出样例
223
测试代码
#include <bits/stdc++.h>
using namespace std;
struct node{
int weight, weighted_path_length;
node(int weight): weight(weight), weighted_path_length(0){}
node(node &left, node &right){
weight = left.weight+right.weight;
weighted_path_length = weight+left.weighted_path_length+right.weighted_path_length;
}
bool operator<(const node &another)const{
return weight > another.weight;
}
};
int main(){
int n;
cin >> n;
priority_queue<node> q;
for(int i=0;i<n;i++){
int w;
cin >> w;
q.push(node(w));
}
while(q.size()>1){ /// 弹出两个最轻的节点,将其合并构造新节点
node l = q.top();
q.pop();
node r = q.top();
q.pop();
q.push(node(l, r));
}
cout << q.top().weighted_path_length << endl;
return 0;
}