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

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<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
int main(){
    char s[100];
    int count1[100];
    int num;
    while(scanf("%s",s)!=EOF){
        int sum=0;
        int max=0;
        priority_queue < int,vector<int>,greater<int> > q;//定义一个小根堆
        int len=strlen(s);
        num=len*8;
        memset(count1,0,sizeof(count1));//将count1数组的初始值全部设为0
        for(int i=0;i<len;i++){
            count1[s[i]]++;
            if(s[i]>max)
                max=s[i];
        }
        for(int i=0;i<=max;i++){
                if(count1[i]!=0){
                    q.push(count1[i]);
                }
        }
        while(!q.empty()){
            int a=q.top();
            q.pop();
            if(!q.empty()){
            int b=q.top();
            q.pop();
            sum=sum+(a+b);
            q.push(a+b);
            }
        }
        printf("%d %d %.1f\n",num,sum,num/(sum*1.0));
    }


}

猜你喜欢

转载自blog.csdn.net/lijunyan5/article/details/80573429