Problem Description
字符的编码方式有多种,除了大家熟悉的ASCII编码,哈夫曼编码(Huffman Coding)也是一种编码方式,它是可变字长编码。该方法完全依据字符出现概率来构造出平均长度最短的编码,称之为最优编码。哈夫曼编码常被用于数据文件压缩中,其压缩率通常在20%~90%之间。你的任务是对从键盘输入的一个字符串求出它的ASCII编码长度和哈夫曼编码长度的比值。
Input
输入数据有多组,每组数据一行,表示要编码的字符串。
Output
对应字符的ASCII编码长度la,huffman编码长度lh和la/lh的值(保留一位小数),数据之间以空格间隔。
Sample Input
AAAAABCD
THE_CAT_IN_THE_HAT
Sample Output
64 13 4.9
144 51 2.8
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(int a[], int low, int high)
{
int x = a[low], i = low, j = high;
if(low >= high)
{
return;
}
while(i < j)
{
if(i < j && a[j] >= x)
j--;
a[i] = a[j];
if(i < j && a[i] <= x)
i++;
a[j] = a[i];
}
a[i] = x;
sort(a,low, i - 1);
sort(a,i + 1, high);
}
int main()
{
char s[1000];
int q[1000];
while(scanf("%s",s)!=EOF)
{
int sum1, sum2 = 0;
int top = 0, rear = 0;
int t[500]= {0};
int len = strlen(s);
sum1 = 8 * len;
int i;
for(i = 0; i < len; i++)
{
t[(int)s[i]]++;
}
for(i = 0; i < 500; i++)
{
if(t[i] != 0)
{
q[top++] = t[i];
}
}
sort(q, 0, top- 1);
while(top != rear)
{
int x1 = q[rear++];
if(top != rear)
{
int x2 = q[rear++];
sum2 = sum2 + (x1 + x2);
q[top++] = x1 + x2;
sort(q, rear, top - 1);
}
}
double sum3=1.0*sum1/sum2;
printf("%d %d %.1lf\n", sum1, sum2,sum3);
}
return 0;
}
浙公网安备 33010602011771号