zoukankan      html  css  js  c++  java
  • 霍夫曼编码(Huffman Coding)

    霍夫曼编码(Huffman Coding)是一种编码方法,霍夫曼编码是可变字长编码(VLC)的一种。

    霍夫曼编码使用变长编码表对源符号(如文件中的一个字母)进行编码,其中变长编码表是通过一种评估来源符号出现机率的方法得到的,出现机率高的字母使用较短的编码,反之出现机率低的则使用较长的编码,这便使编码之后的字符串的平均长度、期望值降低,从而达到无损压缩数据的目的。

    霍夫曼编码的具体步骤如下:

    1)将信源符号的概率按减小的顺序排队。

    2)把两个最小的概率相加,并继续这一步骤,始终将较高的概率分支放在右边,直到最后变成概率1。

    3)画出由概率1处到每个信源符号的路径,顺序记下沿路径的0和1,所得就是该符号的霍夫曼码字。   

    4)将每对组合的左边一个指定为0,右边一个指定为1(或相反)。

    例:现有一个由5个不同符号组成的30个符号的字符串:

    BABACAC ADADABB CBABEBE DDABEEEBB

    1首先计算出每个字符出现的次数(概率):

    2把出现次数(概率)最小的两个相加,并作为左右子树,重复此过程,直到概率值为1

    第一次:将概率最低值3和4相加,组合成7:

     

    第二次:将最低值5和7相加,组合成12:

    第三次:将8和10相加,组合成18:

    第四次:将最低值12和18相加,结束组合:

    3 将每个二叉树的左边指定为0,右边指定为1

    4 沿二叉树顶部到每个字符路径,获得每个符号的编码

    我们可以看到出现次数(概率)越多的会越在上层,编码也越短,出现频率越少的就越在下层,编码也越长。当我们编码的时候,我们是按“bit”来编码的,解码也是通过bit来完成,如果我们有这样的bitset “10111101100″ 那么其解码后就是 “ABBDE”。所以,我们需要通过这个二叉树建立我们Huffman编码和解码的字典表。

    这里需要注意的是,Huffman编码使得每一个字符的编码都与另一个字符编码的前一部分不同,不会出现像’A’:00,  ’B’:001,这样的情况,解码也不会出现冲突。

    霍夫曼编码的局限性

    利用霍夫曼编码,每个符号的编码长度只能为整数,所以如果源符号集的概率分布不是2负n次方的形式,则无法达到熵极限;输入符号数受限于可实现的码表尺寸;译码复杂;需要实现知道输入符号集的概率分布;没有错误保护功能。

    霍夫曼编码实现 (C++实现):

     
    [cpp] view plain copy
     
    1. int main()  
    2. {  
    3.     int n, w;  
    4.     char c;  
    5.     string s;  
    6.   
    7.     cout << "input size of char : ";  
    8.     cin >> n;  
    9.     BinartNodes bn;  
    10.     for(int i = 0; i != n; ++i)  
    11.     {  
    12.         cout << "input char and weight: ";  
    13.         cin >> c >> w;  
    14.         bn.add_Node((Node(c, w)));  
    15.         cin.clear();  
    16.     }  
    17.     while(bn.size() != 1)  
    18.     {  
    19.         Node n1 = bn.pop(),     //获取前两个权重最小的结点  
    20.             n2 = bn.pop();        
    21.         Node h(' ', n1.get_weight() + n2.get_weight());     //新建结点,权重为前两个结点权重和  
    22.         if( n1.get_weight() < n2.get_weight())      //权重较小的结点在新结点左边  
    23.         {  
    24.             h.set(n1, n2);      //设置新结点左右子结点  
    25.         }  
    26.         else  
    27.         {  
    28.             h.set(n2, n1);  
    29.         }  
    30.         bn.add_Node(h);     //将新结点插入到multiset中  
    31.     }  
    32.     encodeing(bn.get_Node(), s);    //编码  
    33.     cout << "input huffman code: ";  
    34.     cin >> s;  
    35.     cout << "decoded chars: ";  
    36.     decoding(bn.get_Node(), s);     //解码  
    37. }  

    Handle.h句柄类:

    [cpp] view plain copy
     
    1. /*Handle.h*/  
    2. //句柄模型类  
    3. template <class Type> class Handle{  
    4. public:  
    5.     Handle(Type *ptr = 0): pn(ptr), use(new size_t(1)) {}  
    6.     Type& operator*();      //重载操作符*  
    7.     Type* operator->();     //重载操作符->  
    8.     const Type& operator*() const;  
    9.     const Type* operator->() const;  
    10.     Handle(const Handle &h): pn(h.pn), use(h.use) { ++*use; }   //复制操作  
    11.     Handle& operator=(const Handle &h);     //重载操作符=,赋值操作  
    12.     ~Handle() {rem_ref(); }     //析构函数  
    13. private:  
    14.     Type *pn;   //对象指针  
    15.     size_t *use;    //使用次数  
    16.     void rem_ref()  
    17.     {  
    18.         if (--*use == 0)  
    19.         {delete pn; delete use; }  
    20.     }  
    21. };  
    22. template <class Type> inline Type& Handle<Type>::operator*()  
    23. {  
    24.     if (pn) return *pn;  
    25.     throw runtime_error("dereference of unbound Handle");  
    26. }  
    27. template <class Type> inline const Type& Handle<Type>::operator*() const  
    28. {  
    29.     if (pn) return *pn;  
    30.     throw runtime_error("dereference of unbound Handle");  
    31. }  
    32. template <class Type> inline Type* Handle<Type>::operator->()  
    33. {  
    34.     if (pn) return pn;  
    35.     throw runtime_error("access through unbound handle");  
    36. }  
    37. template <class Type> inline const Type* Handle<Type>::operator->() const  
    38. {  
    39.     if (pn) return pn;  
    40.     throw runtime_error("access through unbound handle");  
    41. }  
    42. template <class Type> inline Handle<Type>& Handle<Type>::operator=(const Handle &rhs)  
    43. {  
    44.     ++*rhs.use;  
    45.     rem_ref();  
    46.     pn = rhs.pn;  
    47.     use = rhs.use;  
    48.     return *this;  
    49. }  
    Node.h结点类:
     
    [cpp] view plain copy
     
    1. /*Node.h*/  
    2. template <class T> class Handle;      
    3. class Node{  
    4.     friend class Handle<Node>;  //句柄模型类  
    5. public:  
    6.     Node():ch(' '),wei(0), bits(), lc(), rc(){}  
    7.     Node(const char c, const int w):  
    8.         ch(c), wei(w), bits(), lc(), rc(){}  
    9.     Node(const Node &n){ch = n.ch; wei = n.wei; bits = n.bits;  
    10.         lc = n.lc; rc = n.rc; }  
    11.     virtual Node* clone()const {return new Node( *this);}  
    12.     int get_weight() const {return wei;}    //获取权重  
    13.     char get_char() const {return ch; }     //获得字符  
    14.     Node &get_lchild() {return *lc; }       //获得左结点  
    15.     Node &get_rchild() {return *rc; }       //获得右结点  
    16.     void set(const Node &l, const Node &r){     //设置左右结点  
    17.         lc = Handle<Node>(new Node(l));   
    18.         rc = Handle<Node>(new Node(r));}  
    19.     void set_bits(const string &s){bits = s; }      //设置编码  
    20. private:  
    21.     char ch;    //字符  
    22.     int wei;    //权重  
    23.     string bits;    //编码  
    24.     Handle<Node> lc;    //左结点句柄  
    25.     Handle<Node> rc;    //右结点句柄  
    26. };  
    27. inline bool compare(const Node &lhs, const Node &rhs);      //multiset比较函数  
    28. inline bool compare(const Node &lhs, const Node &rhs)     
    29. {  
    30.     return lhs.get_weight()  < rhs.get_weight();  
    31. }  
    32. class BinartNodes{  
    33.     typedef bool (*Comp)(const Node&, const Node&);  
    34. public:  
    35.     BinartNodes():ms(compare) {}    //初始化ms的比较函数  
    36.     void add_Node(Node &n){ms.insert(n); }      //增加Node结点  
    37.     Node pop();     //出结点  
    38.     size_t size(){return ms.size(); }   //获取multiset大小  
    39.     Node get_Node() {return *ms.begin();}       //获取multiset第一个数据  
    40. private:  
    41.     multiset<Node, Comp> ms;  
    42. };  
    43. /*Node.cpp*/  
    44. #include "Node.h"  
    45. Node BinartNodes::pop()       
    46. {  
    47.     Node n = *ms.begin();   //获取multiset第一个数据  
    48.     ms.erase(ms.find(*ms.begin()));     //从multiset中删除该数据  
    49.     return n;  
    50. }  

    霍夫曼编码实现 (C语言实现):

     
    [cpp] view plain copy
     
      1. #include <stdio.h>  
      2. #include<stdlib.h>  
      3. #include<string>  
      4. #include <iostream>  
      5.   
      6. #define MAXBIT      100  
      7. #define MAXVALUE  10000  
      8. #define MAXLEAF     30  
      9. #define MAXNODE    MAXLEAF*2 -1  
      10.   
      11. typedef struct   
      12. {  
      13.     int bit[MAXBIT];  
      14.     int start;  
      15. } HCodeType;        /* 编码结构体 */  
      16. typedef struct  
      17. {  
      18.     int weight;  
      19.     int parent;  
      20.     int lchild;  
      21.     int rchild;  
      22.     char value;  
      23. } HNodeType;        /* 结点结构体 */  
      24.   
      25. /* 构造一颗哈夫曼树 */  
      26. void HuffmanTree (HNodeType HuffNode[MAXNODE],  int n)  
      27. {   
      28.     /* i、j: 循环变量,m1、m2:构造哈夫曼树不同过程中两个最小权值结点的权值, 
      29.     x1、x2:构造哈夫曼树不同过程中两个最小权值结点在数组中的序号。*/  
      30.     int i, j, m1, m2, x1, x2;  
      31.     /* 初始化存放哈夫曼树数组 HuffNode[] 中的结点 */  
      32.     for (i=0; i<2*n-1; i++)  
      33.     {  
      34.         HuffNode[i].weight = 0;//权值   
      35.         HuffNode[i].parent =-1;  
      36.         HuffNode[i].lchild =-1;  
      37.         HuffNode[i].rchild =-1;  
      38.         HuffNode[i].value=' '; //实际值,可根据情况替换为字母    
      39.     } /* end for */  
      40.   
      41.     /* 输入 n 个叶子结点的权值 */  
      42.     for (i=0; i<n; i++)  
      43.     {  
      44.         printf ("Please input char of leaf node: ", i);  
      45.         scanf ("%c",&HuffNode[i].value);  
      46.   
      47.         getchar();  
      48.     } /* end for */  
      49.     for (i=0; i<n; i++)  
      50.     {  
      51.         printf ("Please input  weight of leaf node: ", i);  
      52.         scanf ("%d",&HuffNode[i].weight);  
      53.   
      54.         getchar();  
      55.     } /* end for */  
      56.   
      57.     /* 循环构造 Huffman 树 */  
      58.     for (i=0; i<n-1; i++)  
      59.     {  
      60.         m1=m2=MAXVALUE;     /* m1、m2中存放两个无父结点且结点权值最小的两个结点 */  
      61.         x1=x2=0;  
      62.         /* 找出所有结点中权值最小、无父结点的两个结点,并合并之为一颗二叉树 */  
      63.         for (j=0; j<n+i; j++)  
      64.         {  
      65.             if (HuffNode[j].weight < m1 && HuffNode[j].parent==-1)  
      66.             {  
      67.                 m2=m1;   
      68.                 x2=x1;   
      69.                 m1=HuffNode[j].weight;  
      70.                 x1=j;  
      71.             }  
      72.             else if (HuffNode[j].weight < m2 && HuffNode[j].parent==-1)  
      73.             {  
      74.                 m2=HuffNode[j].weight;  
      75.                 x2=j;  
      76.             }  
      77.         } /* end for */  
      78.         /* 设置找到的两个子结点 x1、x2 的父结点信息 */  
      79.         HuffNode[x1].parent  = n+i;  
      80.         HuffNode[x2].parent  = n+i;  
      81.         HuffNode[n+i].weight = HuffNode[x1].weight + HuffNode[x2].weight;  
      82.         HuffNode[n+i].lchild = x1;  
      83.         HuffNode[n+i].rchild = x2;  
      84.   
      85.         printf ("x1.weight and x2.weight in round %d: %d, %d ", i+1, HuffNode[x1].weight, HuffNode[x2].weight);  /* 用于测试 */  
      86.         printf (" ");  
      87.     } /* end for */  
      88.   
      89. /* end HuffmanTree */  
      90.   
      91. //解码   
      92. void decodeing(char string[],HNodeType Buf[],int Num)  
      93. {  
      94.     int i,tmp=0,code[1024];  
      95.     int m=2*Num-1;  
      96.     char *nump;  
      97.     char num[1024];  
      98.     for(i=0;i<strlen(string);i++)  
      99.     {  
      100.         if(string[i]=='0')  
      101.             num[i]=0;          
      102.         else  
      103.             num[i]=1;                      
      104.     }   
      105.     i=0;  
      106.     nump=&num[0];  
      107.   
      108.     while(nump<(&num[strlen(string)]))  
      109.     {tmp=m-1;  
      110.     while((Buf[tmp].lchild!=-1)&&(Buf[tmp].rchild!=-1))  
      111.     {  
      112.         if(*nump==0)  
      113.         {  
      114.             tmp=Buf[tmp].lchild ;            
      115.         }   
      116.         else tmp=Buf[tmp].rchild;  
      117.         nump++;  
      118.   
      119.     }   
      120.     printf("%c",Buf[tmp].value);                                    
      121.     }  
      122. }  
      123.   
      124. int main(void)  
      125. {  
      126.   
      127.     HNodeType HuffNode[MAXNODE];            /* 定义一个结点结构体数组 */  
      128.     HCodeType HuffCode[MAXLEAF],  cd;       /* 定义一个编码结构体数组, 同时定义一个临时变量来存放求解编码时的信息 */  
      129.     int i, j, c, p, n;  
      130.     char pp[100];  
      131.     printf ("Please input n: ");  
      132.     scanf ("%d", &n);  
      133.     HuffmanTree (HuffNode, n);  
      134.   
      135.     for (i=0; i < n; i++)  
      136.     {  
      137.         cd.start = n-1;  
      138.         c = i;  
      139.         p = HuffNode[c].parent;  
      140.         while (p != -1)   /* 父结点存在 */  
      141.         {  
      142.             if (HuffNode[p].lchild == c)  
      143.                 cd.bit[cd.start] = 0;  
      144.             else  
      145.                 cd.bit[cd.start] = 1;  
      146.             cd.start--;        /* 求编码的低一位 */  
      147.             c=p;                      
      148.             p=HuffNode[c].parent;    /* 设置下一循环条件 */  
      149.         } /* end while */  
      150.   
      151.         /* 保存求出的每个叶结点的哈夫曼编码和编码的起始位 */  
      152.         for (j=cd.start+1; j<n; j++)  
      153.         { HuffCode[i].bit[j] = cd.bit[j];}  
      154.         HuffCode[i].start = cd.start;  
      155.     } /* end for */  
      156.   
      157.     /* 输出已保存好的所有存在编码的哈夫曼编码 */  
      158.     for (i=0; i<n; i++)  
      159.     {  
      160.         printf ("%d 's Huffman code is: ", i);  
      161.         for (j=HuffCode[i].start+1; j < n; j++)  
      162.         {  
      163.             printf ("%d", HuffCode[i].bit[j]);  
      164.         }  
      165.         printf(" start:%d",HuffCode[i].start);  
      166.   
      167.         printf (" ");  
      168.   
      169.     }  
      170.     printf("Decoding?Please Enter code: ");  
      171.     scanf("%s",&pp);  
      172.     decodeing(pp,HuffNode,n);  
      173.     getchar();  
      174.     return 0;  
      175. }  
  • 相关阅读:
    springboot +mybatis 使用PageHelper实现分页,并带条件模糊查询
    jQuery设置点击选中样式,onmouseover和onmouseout事件
    Ajax跨域设置
    Java获取文章的上一篇/下一篇
    Python str / bytes / unicode 区别详解
    Python bytes 和 string 相互转换
    Python bytearray/bytes/string区别
    Python eval 与 exec 函数区别
    Python eval 与 exec 函数
    Python set list dict tuple 区别和相互转换
  • 原文地址:https://www.cnblogs.com/lancidie/p/8662373.html
Copyright © 2011-2022 走看看