哈夫曼树 带权路径长度WPL

 
 
 1002. Huffman coding
 
   
   
 
Time Limit: 1sec    Memory Limit:256MB
Description

In computer science and information theory, a Huffman code is an optimal prefix code algorithm.

In this exercise, please use Huffman coding to encode a given data.

You should output the number of bits, denoted asB(T), to encode the data:

B(T)=∑f(c)dT(c),

wheref(c) is the frequency of character c, and dT(c) is be the depth of characterc's leaf in the tree T.

 
Input

The first line is the number of characters n.

The following n lines, each line gives the character c and its frequencyf(c).

Output

 Output a single number B(T).

Sample Input
Copy sample input to clipboard
5
0 5
1 4
2 6
3 2
4 3
Sample Output
45
Hint
0: 01
1: 00
2: 11
3: 100
4: 101


题目的意思大致是(直接看测试样例)第一行为测试样例数,接下来n行,第一个为字符(不一定是整数的),第二个是字符出现的频率。
此题的一种哈夫曼树形式如下(构造过程见另一篇博客)


(从第0层开始)WPL = 2 * 3(长度为3的编码形式)+3*3 + (4+5+6)*2 = 45;
这是定义的计算WPL的方式,然后我们看一下另一个奇妙的结果20 + 9 + 11 + 5 = 45;

证明如下:(证明并不充分 详细点的证明和讲解


如果知道了这个结论,这种题目的难度完全降没了。接下来就贴代码了。代码太渣 委屈不过还是拿出来 吧
#include<iostream>
#include<algorithm>

using namespace std; 

int main()
{
	int N;
	cin >> N;
	int hafuman[2*N];//some complier don't support.sometimes N should be const. 
	for(int i = 0;i < N;i++)
	{
		char index;
		int fre;
		cin >> index >> fre;
		hafuman[i] = fre;
	} 
	int ans = 0;
	for(int i = 0;i < N-1;i++)
	{
		sort(hafuman+i,hafuman+N);
//		for(int j = i;j < N;j++) cout << hafuman[j] << " " ;
//		cout << endl;
//			cout << ans << " ans " << endl;
		hafuman[i+1] = hafuman[i] + hafuman[i+1];
		ans += hafuman[i+1]; 
	}
	cout << ans << endl;
}


另外还可以用优先队列(用小根堆的),这样就只需要每次比较对首两个元素。
  • 12
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值