哈夫曼编码

来源:互联网 发布:淘宝客服的工作好做吗 编辑:程序博客网 时间:2024/06/05 20:27
#include<stdio.h>
#include<stdlib.h>
#define Max 10001
struct hfmnode{
    int lfou;
    int rfou;
    int lchild;
    int rchild;
    int qnumber;
    char node;
    int xuan;
}th[Max];
int n,i,j;
struct Stack{
    int *top;
    int *base;
}t;
void creathfmtree()
{
    int i,k,j,w,Min;
    int sum=n;
    for(i=0;i<sum-1;i++){
        for(j=0;j<2;j++){
            for(k=0,Min=10000;k<n;k++){
                if(th[k].qnumber<Min&&th[k].xuan==0){
                    Min=th[k].qnumber;
                    w=k;
                }
            }
            if(j==0){
                th[w].xuan=1;
                th[n].lchild=w;
                th[n].qnumber=th[w].qnumber;
                th[n].lfou=0;
                th[n].rfou=0;
            }
            else {
                th[w].xuan=1;
                th[n].xuan=0;
                th[n].qnumber+=th[w].qnumber;
                th[n].rchild=w;
                n++;
            }
        }
    }
}
void makehfmcode()
{
    int i,j,ch[1000],k=0;
    t.base=(int*)malloc(sizeof(int)*1001);
    t.top=t.base;
    *(t.top)=n-1;
    t.top++;
    while(t.top!=t.base){
            int w=*(t.top-1);
        for(i=0;i<2;i++){
            if(th[w].lchild==-1||th[w].rchild==-1){
                for(j=0;j<k;j++){
                    printf("%d ",ch[j]);
                }
                k--;
                printf("\n");
                t.top--;
                break;
            }
            else if(th[w].lfou==0){
                ch[k]=0;
                k++;
                th[w].lfou=1;
                *(t.top)=th[w].lchild;
                t.top++;
                break;
            }
            else if(th[w].rfou==0){
                ch[k]=1;
                k++;
                th[w].rfou=1;
                *(t.top)=th[w].rchild;
                t.top++;
                break;
            }
        }
        if(i==2){
            t.top--;
            k--;
        }
    }
}
int main()
{
    scanf("%d",&n);
    getchar();
    for(i=0;i<n;i++){
        scanf("%c %d",&th[i].node,&th[i].qnumber);
        th[i].lfou=0;
        th[i].rfou=0;
        th[i].lchild=-1;
        th[i].rchild=-1;
        th[i].xuan=0;
        getchar();
    }
    creathfmtree();
    makehfmcode();
    return 0;
}
/*
5
q 3
s 5
t 7
w 8
u 9
*/

0 0
原创粉丝点击