哈夫曼树的WPL值的计算

在计算WPL值的时候一般是用叶子节点的权值乘上其路径长度,但是实际上在构建哈夫曼树的过程中我们其实已经计算过路径长度了,即

WPL = 哈夫曼树中所有非叶子结点的权值之和

举个例子:构造 1 2 2 5 9的哈夫曼树并计算其WPL值。
在这里插入图片描述
上图即为构建出来的HuffmanTree,
WPL= (1+2)* 4 + 3 * 2 + 5 * 2 + 9 =37
这个是使用权值乘以路径长度,但是在计算其中非叶子节点的权值时,3 包含了1个(1+2),5是用3得来的,所以也包含了一个(1+2),同理10和19也是一样,所以如果直接将所有非叶子节点相加
WPL = 3 + 5 + 10 + 19 = 37。
得到的结果是一样的。这在实际计算中可以省去再次迭代计算路径长度的logn的复杂度。


实例:北京邮电大学复试题 哈夫曼树

时间限制:1秒 空间限制:65536K 热度指数:4772
校招时部分企业笔试将禁止编程题跳出页面,为提前适应,练习时请使用在线自测,而非本地IDE。

题目描述

哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。

输入描述:

 

输入有多组数据。 每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。

输出描述:

输出权值。

输入例子:

5
1 2 2 5 9


输出例子:

37

示例1

输入

5
1 2 2 5 9

输出

37

#include <iostream>
#include <queue>
#include <stdlib.h>
#include <stdio.h>
#include <map>
#include <string>
#include <cstdlib>
#include <stack>
#include <vector>
#include <math.h>
#include <algorithm>
#include <typeinfo>
#include <cstring>


using namespace std;

const int maxn = 1003;
int data[maxn];

priority_queue<int ,vector<int> ,greater<int>> q;


int main(int argc, char const *argv[])
{
	int n;
	while(cin>>n){
		while(!q.empty())	q.pop();
		for(int i=0;i<n;i++){
			cin>>data[i];
			q.push(data[i]);
		}
		int ans=0;
		while(q.size()>=2){
			int a=q.top();q.pop();
			int b=q.top();q.pop();
			q.push(a+b);
			ans+=(a+b);
		}
		cout<<ans<<endl;
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章