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

本文介绍了一种计算方法,用以比较输入字符串的ASCII编码与哈夫曼编码的长度,并输出两者的比例。通过构建哈夫曼树来得到每个字符的哈夫曼编码,进而计算出整个字符串的哈夫曼编码总长度。
&spm=1001.2101.3001.5002&articleId=72854014&d=1&t=3&u=255a7e1517e6423e887a59057eb78fd3)
2万+

被折叠的 条评论
为什么被折叠?



