数据结构实验之二叉树六:哈夫曼编码

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
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
void qsort(int a[], int l, int r)
{
    int x = a[l];
    int i = l, j = r;
    if(l>=r) 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;
    qsort(a, l, i-1);
    qsort(a, i+1, r);
}
int main()
{
    char s[1000];
    int t[500];
    int q[1000];
    while(~scanf("%s", s))
    {
        int sum1, sum2 = 0;
        int top = 0, rear = 0;
        memset(t, 0, sizeof(t));
        int len = strlen(s);
        sum1 = 8*len;
        for(int i = 0;i<len;i++)
        {
            t[s[i]]++;
        }
        for(int i = 0;i<500;i++)
        {
            if(t[i]!=0) q[top++] = t[i];
        }
        qsort(q, 0, top-1);
        while(top!=rear)
        {
            int x1 = q[rear++];
            if(top!=rear)
            {
                int x2 = q[rear++];
                sum2 += (x1+x2);
                q[top++] = x1+x2;
                qsort(q, rear, top-1);
            }
        }
        printf("%d %d %.1lf\n", sum1, sum2, 1.0*sum1/sum2);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值