1. 程式人生 > >資料結構實驗之二叉樹六:哈夫曼編碼(最優二叉樹)

資料結構實驗之二叉樹六:哈夫曼編碼(最優二叉樹)

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; }