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

来源:互联网 发布:js对象添加属性的方法 编辑:程序博客网 时间:2024/06/06 09:04

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;}
阅读全文
0 0
原创粉丝点击