哈夫曼树的简单实现(JLOJ2370)

//哈夫曼编码板子
#include<iostream>
#include<cstdio>
#define MAXLEAF (50)
#define MAXNODE (2*MAXLEAF - 1)
#define MAXCODE (300) //最大编码位数
#define MAXVALUE (0x3f3f3f3f)
using namespace std;
typedef struct
{
    int weight;
    int parent;
    int lchild;
    int rchild;
}huffnode;//哈夫曼叶子节点
typedef struct code
{
    int start;
    int bits[MAXCODE];
}huffcode;//哈夫曼编码
void HuffManTree(huffnode arr[],int n)//n为哈夫曼树中叶子节点的个数
{
    int pos1,pos2,w1,w2;
    for(int i=0;i!=n-1;++i)//哈夫曼树n个节点,构建n-1次
    {
        pos1 = pos2 = 0;
        w1 = w2 = MAXVALUE;
        for(int j=0;j<n+i;++j)
        {//找出权值最小的俩个值
            if(arr[j].parent==-1&&arr[j].weight<w1)
            {
                pos2 = pos1;
                w2 = w1;//代替w1
                pos1 = j;
                w1 = arr[j].weight;
            }else
            if(arr[j].parent==-1&&arr[j].weight<w2)
            {
                pos2 = j;
                w2 = arr[j].weight;
            }
        }
        arr[pos1].parent = n+i;//父节点的编码
        arr[pos2].parent = n+i;
        arr[n+i].lchild = pos1;
        arr[n+i].rchild = pos2;
        arr[n+i].weight = arr[pos1].weight + arr[pos2].weight;//构建出了新的节点
    }
}//构建哈夫曼树
void HuffManCode(huffnode arr[],int n)//哈夫曼编码
{
    HuffManTree(arr,n);//建树
    huffcode Code[MAXNODE],tmp;
    for(int i=0;i!=n;++i)
    {//自顶向下构建编码
        tmp.start = n;
        int cur = i;//当前节点
        int parent = arr[cur].parent;
        while(parent != -1)
        {
            if(arr[parent].lchild==cur)
                tmp.bits[tmp.start] = 0;//左孩子
            else
                tmp.bits[tmp.start] = 1;//右孩子
            --tmp.start;//自顶向下编码
            cur = parent;//向上编码
            parent = arr[cur].parent;
        }
        ++tmp.start;
        for(int j= tmp.start;j<=n;++j)
            Code[i].bits[j] = tmp.bits[j];//拷贝编码
        Code[i].start = tmp.start;
    }//编码
    for(int i=0;i!=n;++i)
    {
        for(int j=Code[i].start;j<=n;++j)
            cout<<Code[i].bits[j];
        cout<<endl;
    }
}
int main()
{
    int n;//个数
    huffnode huff_node[MAXNODE];
    cin>>n;
    for(int i=0;i!=2*n-1;++i)
    {
        huff_node[i].lchild = huff_node[i].parent = huff_node[i].rchild = -1;
        huff_node[i].weight = 0;
    }//初始化叶子节点
    for(int i=0;i!=n;++i)
        cin>>huff_node[i].weight;//输入叶子节点权值
    HuffManCode(huff_node,n);
    return 0;
}

 

posted on 2019-08-29 17:12  chengyulala  阅读(300)  评论(0编辑  收藏  举报

导航