其他分享
首页 > 其他分享> > HuffmanTree

HuffmanTree

作者:互联网

#include<stdio.h>
#include<stdlib.h>

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

void Select(HuffmanTree &HT,int n,int &s1,int &s2)
{
    int i;
    for(i=1;i<=n;i++)
        if(HT[i].parent==0)
        {
            s1=i;
            break;
        }
    for(i=s1;i<=n;i++)
    {
        if(HT[i].parent==0&&HT[i].weight<HT[s1].weight)
            s1=i;
    }
    //find s1
    for(i=1;i<=n;i++)
        if(HT[i].parent==0&&i!=s1)
        {
            s2=i;
            break;
        }
    for(i=s2;i<=n;i++)
    {
        if(HT[i].parent==0&&HT[i].weight<HT[s2].weight&&s1!=i)
            s2=i;
    }
}

int res(HuffmanTree &H,int n,int m)
{
    if(H[m].lchild==0)
        return H[m].weight*n;
    return res(H,n+1,H[m].lchild)+res(H,n+1,H[m].rchild);
}
void CreateHuffmanTree(HuffmanTree &HT,int n)
{
    int m,i;
    int s1,s2;
    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;}
    for(i=1;i<=n;i++)
        scanf("%d",&HT[i].weight);

    for(i=n+1;i<=m;i++)
    {
        Select(HT,i-1,s1,s2);
        printf("%d %d\n",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;
    }
    printf("%d",res(HT,1,m));
}

int main()
{
    int n;
    HuffmanTree Q;
    scanf("%d",&n);
    CreateHuffmanTree(Q,n);
    return 0;
}

 

标签:lchild,typedef,parent,int,HuffmanTree,include
来源: https://www.cnblogs.com/1328497946TS/p/11081832.html