HDU 1053 哈弗曼编码

典型的哈弗曼编码。借助优先队列,当输入只有一种符号的时候需要另作讨论


#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct node{
	friend bool operator<(const node a,const node b)
	{
		return a.w>b.w;
	}
	int w;
};
int main()
{
	char b[10005];
	int ans;
	while(scanf("%s",b)&&strcmp(b,"END")!=0)
	{
		ans=0;
		priority_queue<node>q;
		int i;
		int a[300];
		memset(a,0,sizeof(a));
		int len=strlen(b);
		for(i=0;i<len;i++)
			a[b[i]]++;
		for(i=0;i<=256;i++)
		{
			if(a[i]>0)
			{
				node s;
				s.w=a[i];
				q.push(s);
			}
		}
		int sum=0;
		if(q.size()==1)
		{
			ans=len;
		}
		else
		{
			while(q.size()!=1)
			{
				int tmp;
				node t,tmp1,tmp2;
				tmp1=q.top();
				q.pop();
				tmp2=q.top();
				q.pop();
				tmp=tmp1.w+tmp2.w;
				t.w=tmp;
				sum+=tmp;
				q.push(t);
			}
			ans=sum;
		}
		printf("%d %d %.1lf\n",len*8,ans,len*8.0/ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值