HuffmanTree

Posted Mr.Yao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

 

以上是关于HuffmanTree的主要内容,如果未能解决你的问题,请参考以下文章

HuffmanTree

C++项目:基于HuffmanTree实现文件的压缩与解压缩

构造Huffman以及实现

(哈夫曼树)HuffmanTree的java实现

HuffmanTree的浅析和在C#中的算法实现

HuffmanTree的浅析和在C#中的算法实现