【问题描述】
题目来源:https://www.acwing.com/problem/content/3534/
给定 N 个权值作为 N 个叶子结点,构造一棵二叉树,若该树的带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树(Huffman Tree)。树的带权路径长度规定为所有叶子结点的带权路径长度之和,记为 WPL。WPL示例如下:
【输入格式】
第一行包含整数 N,表示叶子结点数量。
第二行包含 N 个整数,表示每个叶子结点的权值。
【输出格式】
输出一个整数,表示生成哈夫曼树的带权路径长度。
【数据范围】
2≤N≤1000,叶子结点的权值范围 [1,100]。
【输入输出样例】
输入样例:
5
1 2 2 5 9
输出样例:
37
【算法代码】
#include <bits/stdc++.h>
using namespace std;
priority_queue<int,vector<int>,greater<int> > Q;
int total;
int n,x;
int main() {
cin>>n;
while(n--) {
cin>>x;
Q.push(x);
}
while(Q.size()!=1) {
int sum=0;
sum+=Q.top();
Q.pop();
sum+=Q.top();
Q.pop();
Q.push(sum);
total+=sum;
}
cout<<total;
return 0;
}
/*
in:
5
1 2 2 5 9
out:
37
*/
【参考文献】
https://blog.csdn.net/wei_wu_xian_/article/details/107080981
https://www.acwing.com/problem/content/3534/