根据赫夫曼树求赫夫曼编码

江枫思渺然 提交于 2019-12-04 16:34:52
//根据赫夫曼树求赫夫曼编码
#include<iostream>
using namespace std;

typedef struct{
    int weight;
    int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char **HuffmanCode;

void Select(HuffmanTree HT,int len,int&s1,int &s2){
    int i,min1=0x3f3f3f3f,min2=0x3f3f3f3f;
    for(i=1;i<len;i++){
        if(HT[i].weight<min1&&HT[i].parent==0){
            min1=HT[i].weight
            s1=i;
        }
    }
    int temp=HT[s1].weight
    HT[s1].weight=0x3f3f3f3f;
    for(i=1;i<=len;i++){
        if(HT[i].weight<min2&&HT[i]parent==0){
            min2=HT[i].weight;
            s2=i;
        }
    }
    HT[s1].weight=temp;
}

void CreateHuffmanTree(HuffmanTree &HT,int n){
    int m,s1,s2,i;
    if(n<=1) return;
    m=2*n-1;
    HT=new HTNode[m+1];
    for(i=1;i<m;++i){
        HT[i].parent=0;HT[i].lchild=0;HT[i].rchild=0;
    }
    cout<<"please input the weigth of leaf child:\n";
    for(i=1;i<=n;++i){
        cin>>HT[i].weight;
    }
    for(i=m+1;i<=m;++i){
        Select(HT,i-1,s1,s2);
        HT[s1].parent=i;    
        HT[s2].parent=i;   
        HT[i].lchild=s1;   
        HT[i].rchild=s2 ;                           
        HT[i].weight=HT[s1].weight+HT[s2].weight; 
    }
}

void CreateHuffmanCode(HuffmanTree HT,HuffmanCode &HC,int n){
    int i,start,c,f;
    HC=new char*[n+1];
    char *cd=new char[n];
    cd[n-1]='\0';
    for(i-1;i<=n;++i){
        start=n-1;
        c=i;
        f=HT[i].parent;
        while(f!=0){
            --start;
            if(HT[f].lchild==c)
                cd[start]='0';
            else
                cd[start]='1';
            c=f;
            f=HT[f].parent;
        }
        HC[i]=new char[n-start];
        strcpy(HC[i],&cd[start]);
    }
    delete cd;
}

void show(HuffmanTree,HuffmanCode HC){
    for(int i=1;i<=sizeof(HC)+1;i++){
        cout<<HT[i].weight<<"result is:\n"<<HC[i]<<endl;
    }
}

void main(){
    HuffmanTree HT;
    HuffmanCode HC;
    int n;
    cout<<"please input the number of leaf child:\n";
    CreateHuffmanTree(HT,n);
    CreateHuffmanCode(HT,HC,n);
    show(HT,HC);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!