数据结构——哈夫曼树求最小WPL(树的带权路径长度)

给出代码与注释

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

//代表小堆顶的优先队列
priority_queue<long long, vector<long long>, greater<long long>>q;

int main(void)
{
	int n;
	long long temp, x, y, ans = 0;
	cout << "输入权值个数:";
	cin >> n;
	cout << "输入所有的权值:" << endl;
	for (int i = 0; i < n; i++)
	{
		cin >> temp;
		q.push(temp);//录入所有的初始权重
	}
	while (q.size() > 1)//当优先队列中元素个数大于等于2时
	{
		x = q.top();
		q.pop();
		y = q.top();
		q.pop();
		q.push(x + y);//取出堆顶的两个元素,求和后压入优先队列
		ans += x + y;//ans是最终求和结果
	}
	cout << ans << endl;//输出最小WPL
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41938259/article/details/86311294