复旦16年机考题--哈夫曼编码--Safe Or Unsafe HDU - 2527

题目是是给定一个字符串,求哈夫曼编码的最短长度,没有找到原题,故用HUD-2527来代替。
解题思路:思路是哈夫曼树的非叶子结点权值和为哈夫曼编码的最短长度,使用优先队列来实现。值得注意的是aaaa 的哈夫曼编码为其长度,为4。

#include <iostream>
#include <string>
#include <queue>
#include <cstring>

using namespace std;

priority_queue<int , vector<int>, greater<int> > q;    //小的先出队 
int list[26];

int main()
{
	int n, m;
	string str;
	cin >> n;
	while(n--)
	{
		cin >> m;
		cin >> str;
		while(!q.empty())   //清空 
			q.pop();
		memset(list, 0, sizeof(list));
		
		for(int i = 0; i < str.length(); i++)
			list[str[i]-'a']++;
		for(int i = 0; i < 26; i++)
			if(list[i])
				q.push(list[i]);
			
		int ans = 0;
		if(q.size() > 1)
			while(q.size() > 1)
			{
				int x1 = q.top();
				q.pop();
				int x2 = q.top();
				q.pop();
				ans += (x1 + x2);   //依次累加非叶子结点。
				q.push(x1+x2);
			}
		else    //4 aaaaa 哈夫曼编码为5输出no 
			ans = q.top(); 
		if(ans <= m)
			cout << "yes" << endl;
		else
			cout << "no" << endl;
	}	
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值