哈夫曼树

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<queue>
#include<algorithm>
const int maxn=1007;
const int INF=0x3f3f3f3f;
using namespace std;

typedef struct node
{
    char ch;
    int weight;
    int parent, lchild, rchild;
}huffNode;


void SelectionMin(huffNode T[], int k, int &x1, int &x2)
{
    int min1, min2;
    int d1, d2;
    min1=min2=INF;

    for(int i=0; i<k; i++)
    {
        if(T[i].weight<min1 && T[i].parent==-1)
        {
            min2=min1;
            d2=d1;
            min1=T[i].weight;
            d1=i;
        }
        else if(T[i].weight<min2 && T[i].parent==-1)
        {
            min2=T[i].weight;
            d2=i;
        }
    }
    x1=d1;
    x2=d2;
}

void huffman(int n, int w[], huffNode T[])
{
    for(int i=0; i<2*n-1; i++)
    {
        T[i].parent=-1;
        T[i].lchild=-1;
        T[i].rchild=-1;
        if(i<n)
            T[i].weight=w[i];
        else
            T[i].weight=-1;
    }

    int x1,x2;
    for(int k=n; k<2*n-1; k++)
    {
        SelectionMin(T, k, x1, x2);
        T[x1].parent=T[x2].parent=k;
        T[k].weight=T[x1].weight+T[x2].weight;
        T[k].lchild=x1;
        T[k].rchild=x2;
    }
}

void Display(int n, huffNode T[])
{
    for(int i=0; i<2*n-1; i++)
    {
        printf("%-5d %-5d %-5d %-5d %-5d
", i, T[i].weight, T[i].parent, T[i].lchild, T[i].rchild);
    }
    printf("
");
}

void getcode(int k, char str[], huffNode T[])
{
    int i=0, p=0;
    while(T[k].parent!=-1)
    {
        p=T[k].parent;
        if(k==T[p].lchild)
            str[i++]='0';
        else
            str[i++]='1';
        k=p;
    }
    str[i]='';
    strrev(str);
}

void huffcode(huffNode T[], int n)
{
    char str[100];
    memset(str, 0, sizeof(str));
    for(int i=0; i<2*n-1; i++)
    {
        getcode(i, str, T);
        printf("%d: %s
", T[i].weight, str);
    }
}
int main()
{
    huffNode T[maxn];
    int w[]={30, 25, 20, 10, 10, 5};
    huffman(6, w, T);
    Display(6, T);

    huffcode(T, 6);
    return 0;
}
原文地址:https://www.cnblogs.com/w-y-1/p/6710840.html