Description
字符的编码方式有多种,除了大家熟悉的ASCII编码,哈夫曼编码(Huffman Coding)也是一种编码方式,它是可变字长编码。该方法完全依据字符出现概率来构造出平均长度最短的编码,称之为最优编码。哈夫曼编码常被用于数据文件压缩中,其压缩率通常在20%~90%之间。你的任务是对从键盘输入的一个字符串求出它的ASCII编码长度和哈夫曼编码长度的比值。
Input
输入数据有多组,每组数据一行,表示要编码的字符串。
Output
对应字符的ASCII编码长度la,huffman编码长度lh和la/lh的值(保留一位小数),数据之间以空格间隔。
Sample
Input
AAAAABCD
THE_CAT_IN_THE_HAT
Output
64 13 4.9
144 51 2.8
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
char s[100005];
int Max,len,sum;
int cnt[256];
while(cin>>s)
{
priority_queue <int ,vector<int>, greater<int> > q;
memset(cnt,0,sizeof(cnt));
len = strlen(s);
Max = 0;
sum = 0;
for(int i=0;i<len;i++)
{
cnt[s[i]]++;
if(s[i]>Max)
Max = s[i];
}
for(int i=0;i<=Max;i++)
if(cnt[i] != 0)
q.push(cnt[i]);
while(!q.empty())
{
int a = q.top();
q.pop();
if(!q.empty())
{
int b = q.top();
q.pop();
sum += (a+b);
q.push(a+b);
}
}
printf("%d %d %.1f\n",len*8,sum,len*8.0/sum);
}
return 0;
}