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

本文介绍了一种计算字符串ASCII编码与哈夫曼编码长度比的方法,通过构造哈夫曼树实现数据压缩,展示了如何使用C++实现哈夫曼编码,并计算不同字符串的压缩效果。

数据结构实验之二叉树六:哈夫曼编码
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
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
Hint

Author

xam


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;


const int MAX = 300;
typedef struct node
{
    int data;
    struct node *next;
    struct node *pre;
} d;
void push(d * &head, int em)
{
    d *t = new d;
    t->data = em;
    t->next = NULL;
    t->pre = NULL;
    d *p;
    if (head == NULL)
    {
        head = t;
        return;
    }
    if (em >= head->data)
    {
        t->next = head;
        head->pre = t;
        head = t;
        return;
    }
    p = head;
    while (p != NULL)//p->next != NULL就不能到最后一个元素了
    {
        if (em >= p->data)
        {
            d *tp;
            tp = p->pre;
            tp->next = t;
            t->pre = tp;
            t->next = p;
            p->pre = t;
            break;
        }
        //当前数是最小数时
        if (p->next == NULL)
        {
            p->next = t;
            t->pre = p;
            break;
        }
        p = p->next;
    }
}

int main()
{
    char str[MAX];
    while (cin >> str)
    {
        int suma = 0, sumh = 0;
        int len = strlen(str);
        suma = len * 8;
        int cth[MAX] = { 0 };
        d *head;
        head = NULL;
        d *a, *b;
        int ct = 0;
        int i = 0;
        while (i < len)
        {
            cth[str[i]]++;
            i++;
        }
        i = 0;
        while (i < MAX)
        {
            if (cth[i] != 0)
            {
                ct++;
                push(head, cth[i]);
            }
            i++;
        }
        if (ct == 1)
        {
            sumh = head->data;
        }
        //计算次数
        while (ct >= 2)
        {
            a = head;
            while (a->next != NULL)//找到最后一个数
            {
                a = a->next;
            }
            b = a->pre;
            int t;
            t = b->data + a->data;
            sumh += t;
            //b = NULL;
            b = b->pre;
            if (b == NULL)//注意b是队列头
                break;
            b->next = NULL;
            push(head, t);
            ct--;
        }
        double aa = (double)suma / sumh;
        printf("%d %d %.1lf\n", suma, sumh, aa);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值