huffman编码

来源:互联网 发布:类似知乎的精英平台 编辑:程序博客网 时间:2024/04/19 07:38
  1. #include<iostream>
  2. #include<stdlib.h>
  3. #include<string>
  4. using namespace std;
  5. #define MAX 1000
  6. typedef char ElemType;
  7. typedef int PerType;
  8. typedef struct Elem{
  9.       ElemType data;
  10.       PerType percent;
  11.       string value;
  12.         }Elem;
  13. typedef struct {
  14.         PerType weight;
  15.         int parent,lchild,rchild;
  16.         }HTNode,*HuffmanTree;
  17. void Input(Elem *(&a),int n)
  18. {
  19.    if(!(a=new Elem[n])) exit(1);
  20.    for(int i=0;i<n;i++)
  21.    cin>>a[i].data>>a[i].percent;  }
  22. void Huffman(HuffmanTree &h,Elem *a,int n)
  23. {
  24.     int m=2*n-1,i=0,j,m1,m2,x1,x2;
  25.    if(!(h=new HTNode[m])) exit(1);
  26.  for(;i<n;i++)
  27.        {
  28.             h[i].weight=a[i].percent;
  29.             h[i].parent=h[i].lchild=h[i].rchild=-1;}
  30.     for(;i<m;i++)
  31.        {
  32.             h[i].weight=0;
  33.             h[i].parent=h[i].lchild=h[i].rchild=-1;}
  34.     for(i=0;i<n-1;i++)
  35.        {
  36.            m1=m2=MAX;
  37.            x1=x2=0;
  38.            for(j=0;j<n+i;j++)
  39.               if(h[j].parent==-1&&h[j].weight<m1)
  40.                  {
  41.                     m2=m1;x2=x1;
  42.                     m1=h[j].weight; 
  43.                     x1=j;}      
  44.               else if(h[j].parent==-1&&h[j].weight<m2)
  45.                 {
  46.                     m2=h[j].weight;
  47.                     x2=j; }
  48.     if(x1>x2) x1^=x2^=x1^=x2;
  49.           h[x1].parent=h[x2].parent=n+i;
  50.           h[n+i].weight=h[x1].weight+h[x2].weight;
  51.           h[n+i].lchild=x1;
  52.           h[n+i].rchild=x2;}
  53.     
  54.     int c,f;
  55.     for(i=0;i<n;i++)
  56.     {  
  57.        string s;
  58.        for(c=i,f=h[i].parent;f!=-1;c=f,f=h[f].parent)
  59.          {
  60.              if(h[f].lchild==c) s="0"+s;
  61.              else s="1"+s;}
  62.        a[i].value=s; }
  63. }
  64. void print(Elem *a,int n)
  65. {
  66. for(int i=0;i<n;i++)
  67. cout<<a[i].data<<" "<<a[i].value<<endl;
  68. cout<<endl;}
  69. string Match(Elem *a,ElemType c,int n)
  70. {
  71.   int i=0;
  72.   for(;i<n;i++)
  73.     if(a[i].data==c)   return a[i].value;
  74.   if(i==n)exit(1); }      
  75.        
  76.        
  77. int main()
  78. {
  79.     int n;
  80.     Elem *a;
  81.     string s;
  82.     HuffmanTree h;
  83.     cin>>n;
  84.     Input(a,n);
  85.     Huffman(h,a,n);
  86.  print(a,n);
  87.  while(cin>>s)
  88.     {for(size_t i=0;i<s.size();i++)
  89.   cout<<Match(a,s[i],n);
  90.  cout<<endl;}
  91.     return 0;
  92.     }