构造哈夫曼数及哈夫曼编码

/*构造哈夫曼数及哈夫曼编码*/
#include<iostream>
using namespace std;
#define Maxlen 100
typedef struct 
{
    int weight;
    int lchild,rchild,parent;
}HTNode;
typedef HTNode Hfmt[Maxlen];
int n;
void InitHfmt(Hfmt T)
{
    int i;
    printf("\n\t\t请输入共有多少个权值(小于50):");
    scanf(" %d",&n);
    getchar();
    for(i=0;i<2*n-1;i++)
    {
        T[i].weight=0;T[i].lchild=-1;
        T[i].rchild=-1;T[i].parent=-1;
    }
}
void InputWeight(Hfmt T)
{
    int w;
    int i;
    for(i=0;i<n;i++)
    {
        printf("\n\t\t输入第%d个权值:",i+1);
        scanf("%d",&w);
        getchar();
        //cin>>w;
        T[i].weight=w;
    }
}
void SelectMin( Hfmt T,int i,int *p1,int *p2)
{
    int min1=9999;
    int min2=9999;
    int j;
    for(j=0;j<=i;j++)
    {
        if(T[j].parent==-1)
        {
            if(min1>T[j].weight)
            {
                min1=T[j].weight;
                *p1=j;
            }
        }
    }
    for(j=0;j<=i;j++)
    {
        if(T[j].parent==-1)
        {
            if(min2>T[j].weight&&j!=(*p1))
            {
                min2=T[j].weight;
                *p2=j;
            }
        }
    }
}
void CreatHfmt(Hfmt T)
{
    int i,p1,p2;
    InitHfmt(T);
    InputWeight(T);
    for(i=n;i<2*n-1;i++)
    {
        SelectMin(T,i-1,&p1,&p2);
        T[p1].parent=T[p2].parent=i;
        T[i].lchild=p1;
        T[i].rchild=p2;
        T[i].weight=T[p1].weight+T[p2].weight;
    }
}
void PrintHfmt(Hfmt T)
{
    int i,k=0;
    for(i=0;i<2*n-1;i++)
        while(T[i].lchild!=-1)
        {
            if(!(k%2))
                printf("\n");
            printf("\t\t(%d  %d),(%d  %d)",T[i].weight,T[T[i].lchild].weight,
                T[i].weight,T[T[i].rchild].weight);
            k++;
            break;
        }
}
void hfnode(Hfmt T,int i,int j)
{
    j=T[i].parent;
    if(T[j].rchild==i)
        printf("1");
    else
        printf("0");
    if(T[j].parent!=-1)
    {
        i=j;
        hfnode(T,i,j);
    }
}
void huffmannode(Hfmt T)
{
    int i,j,a,k=0;
    printf("\n");
    for(i=0;i<n;i++)
    {
        j=0;a=i;
        if(!(k%2))
            printf("\n");
        printf("\t\t%d: ",T[i].weight);
        k++;
        hfnode(T,i,j);
        i=a;
    }
}
int main()
{
    Hfmt Ht;
    CreatHfmt(Ht);
    PrintHfmt(Ht);
    huffmannode(Ht);
    printf("\n");
    return 0;
}
posted @ 2012-11-13 20:32  myth_HG  阅读(400)  评论(0编辑  收藏  举报