- #include<iostream>
- #include<stdlib.h>
- #include<string>
- using namespace std;
- #define MAX 1000
- typedef char ElemType;
- typedef int PerType;
- typedef struct Elem{
- ElemType data;
- PerType percent;
- string value;
- }Elem;
- typedef struct {
- PerType weight;
- int parent,lchild,rchild;
- }HTNode,*HuffmanTree;
- void Input(Elem *(&a),int n)
- {
- if(!(a=new Elem[n])) exit(1);
- for(int i=0;i<n;i++)
- cin>>a[i].data>>a[i].percent; }
- void Huffman(HuffmanTree &h,Elem *a,int n)
- {
- int m=2*n-1,i=0,j,m1,m2,x1,x2;
- if(!(h=new HTNode[m])) exit(1);
- for(;i<n;i++)
- {
- h[i].weight=a[i].percent;
- h[i].parent=h[i].lchild=h[i].rchild=-1;}
- for(;i<m;i++)
- {
- h[i].weight=0;
- h[i].parent=h[i].lchild=h[i].rchild=-1;}
- for(i=0;i<n-1;i++)
- {
- m1=m2=MAX;
- x1=x2=0;
- for(j=0;j<n+i;j++)
- if(h[j].parent==-1&&h[j].weight<m1)
- {
- m2=m1;x2=x1;
- m1=h[j].weight;
- x1=j;}
- else if(h[j].parent==-1&&h[j].weight<m2)
- {
- m2=h[j].weight;
- x2=j; }
- if(x1>x2) x1^=x2^=x1^=x2;
- h[x1].parent=h[x2].parent=n+i;
- h[n+i].weight=h[x1].weight+h[x2].weight;
- h[n+i].lchild=x1;
- h[n+i].rchild=x2;}
- int c,f;
- for(i=0;i<n;i++)
- {
- string s;
- for(c=i,f=h[i].parent;f!=-1;c=f,f=h[f].parent)
- {
- if(h[f].lchild==c) s="0"+s;
- else s="1"+s;}
- a[i].value=s; }
- }
- void print(Elem *a,int n)
- {
- for(int i=0;i<n;i++)
- cout<<a[i].data<<" "<<a[i].value<<endl;
- cout<<endl;}
- string Match(Elem *a,ElemType c,int n)
- {
- int i=0;
- for(;i<n;i++)
- if(a[i].data==c) return a[i].value;
- if(i==n)exit(1); }
- int main()
- {
- int n;
- Elem *a;
- string s;
- HuffmanTree h;
- cin>>n;
- Input(a,n);
- Huffman(h,a,n);
- print(a,n);
- while(cin>>s)
- {for(size_t i=0;i<s.size();i++)
- cout<<Match(a,s[i],n);
- cout<<endl;}
- return 0;
- }
huffman编码
最新推荐文章于 2022-02-25 21:57:21 发布