樹和二叉樹的基本運算實現-哈夫曼樹/哈夫曼編碼

kewlgrl發表於2016-06-15

問題及程式碼:

設計一個程式exp7-6.cpp,構造一棵哈夫曼樹,輸出對應的哈夫曼編碼和平均查詢長度。並用表7.8所示的資料進行驗證。

表7.8 單詞及出現的頻度

單詞

The

of

a

to

and

in

that

he

is

at

on

for

His

are

be

出現頻度

1192

677

541

518

462

450

242

195

190

181

174

157

138

124

123


/*
* Copyright (c) 2016, 煙臺大學計算機與控制工程學院
* All rights reserved.
* 檔名稱:Huffman.cpp
* 作    者:單昕昕
* 完成日期:2016年6月13日
* 版 本 號:v1.0
*/
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define inf 999999
#define MAXN 100

typedef struct//樹中每個節點的型別
{
    string data;//節點值
    double weight;//權重
    int parent,lchild,rchild;//雙親和左右孩子節點
} HTNode;
HTNode ht[MAXN];

typedef struct//存放每個節點哈夫曼編碼的結構
{
    char cd[MAXN];//存放當前節點的哈夫曼編碼
    int start;//存放該節點哈夫曼編碼的起始位置,編碼為cd[start]~cd[n]
} HCode;
HCode hcd[MAXN];

void CreateHT(HTNode ht[],int n)//構造哈夫曼樹
{
    int i,k,lnode,rnode;
    double min1,min2;
    for(i=0; i<2*n-1; ++i)
        ht[i].parent=ht[i].lchild=ht[i].rchild=-1;
    for(i=n; i<2*n-1; ++i)
    {
        min1=min2=inf;
        lnode=rnode=-1;
        for(k=0; k<=i-1; ++k)
            if(ht[k].parent==-1)
            {
                if(ht[k].weight<min1)
                {
                    min2=min1;
                    rnode=lnode;
                    min1=ht[k].weight;
                    lnode=k;
                }
                else if(ht[k].weight<min2)
                {
                    min2=ht[k].weight;
                    rnode=k;
                }
            }
        ht[i].weight=ht[lnode].weight+ht[rnode].weight;
        ht[i].lchild=lnode;
        ht[i].rchild=rnode;
        ht[lnode].parent=i;
        ht[rnode].parent=i;
    }
}

void CreateHCode(HTNode ht[],HCode hcd[],int n)//根據哈夫曼樹求哈夫曼編碼
{
    int i,f,c;
    HCode hc;
    for(i=0; i<n; ++i)
    {
        hc.start=n;
        c=i;
        f=ht[i].parent;
        while(f!=-1)
        {
            if(ht[f].lchild==c)
                hc.cd[hc.start--]='0';
            else
                hc.cd[hc.start--]='1';
            c=f;
            f=ht[f].parent;
        }
        hc.start++;
        hcd[i]=hc;
    }
}

void Display(HTNode ht[],HCode hcd[],int n)
{
    int i,k;
    int sum=0,m=0,cnt;
    cout<<"輸出哈夫曼編碼:"<<endl;
    for (i=0; i<n; i++)
    {
        cnt=0;
        cout<<"\t"<<ht[i].data<<"\t"<<":";
        for (k=hcd[i].start; k<=n; k++)
        {
            cout<<hcd[i].cd[k];
            cnt++;
        }
        m+=ht[i].weight;
        sum+=(ht[i].weight*cnt);
        cout<<endl;
    }
    cout<<"平均長度="<<1.0*sum/m<<endl;
}

int main()
{
    int n=15;
    string str[n]= {"The","of","a","to","and","in","that","he","is","at","on","for","His","are","be"};
    int frq[n]= {1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123};
    for (int i=0; i<n; i++)
    {
        ht[i].data=str[i];
        ht[i].weight=frq[i];
    }
    CreateHT(ht,n);
    CreateHCode(ht,hcd,n);
    Display(ht,hcd,n);
    return 0;
}


執行結果:



相關文章