哈夫曼树代码


#include<cstdio>
#include<iostream>
using namespace std;
#include<cstring>
#include<limits.h>
#include<algorithm>

const int maxn = 1010;
typedef struct{
    int weight;
    char s;
    int parent,lchild,rchild;
}HTNode,HuffmanTree[maxn];

void twoSelect(HuffmanTree HT,int n,int &s1,int &s2)
{
    int max1 = INT32_MAX,max2 = max1;
   
    for (int i = 1; i <= n; ++i)
    {
        if(HT[i].weight < max1 && HT[i].parent == 0){
            max2 = max1;
            s2 = s1;
            max1 = HT[i].weight;
            s1 = i;
        }else if(HT[i].weight < max2 && HT[i].parent == 0){
            max2 = HT[i].weight;
            s2 = i;
        }
    }
    if( s1 > s2) swap(s1,s2);
   // printf("%d %d\n",max1,max2);
   // printf("\n");
}

void createHuffmanTree(HuffmanTree HT,int n,int *weight)
{
    int s1,s2;
    for (int i = 1; i <= n; ++i,++weight)
    {
        HT[i].weight = *weight;
        HT[i].parent = HT[i].lchild = HT[i].rchild = 0;
    }
    for (int i = n+1; i <= 2 * n - 1; ++i)
    {
        twoSelect(HT,i-1,s1,s2);
        HT[s1].parent = HT[s2].parent = i;
        HT[i].lchild = s1;
        HT[i].rchild = s2;
        HT[i].parent = 0;
        HT[i].weight = HT[s1].weight + HT[s2].weight;
    }
}

char** HuffmanTreeCoding(HuffmanTree HT,int n)
{
    if(n <= 1) return NULL;
    int m = 2 * n - 1;
    // char *cd = (char *)malloc(n * sizeof(char)) ;
    // char** hc = (char **)malloc((n+1) * sizeof(char *));
    char *cd = new char[n];
    char **hc = new char*[n+1];
    int start,p,now;
    cd[n-1] = '\0';
    for (int i = 1; i <= n; ++i)
    {
        start = n - 1;
        p = HT[i].parent;
        now = i;
        while(p != 0){
            --start;
            if(HT[p].lchild == now){
                cd[start] = '0';
            }else{
                cd[start] = '1';
            }
            now = p;
            p = HT[p].parent;
        }
        //hc[i] = (char *)malloc( (n - start) * sizeof(char));
        hc[i] = new char[n-start];
        strcpy(hc[i],&cd[start]);
    }
    delete[] cd;
    return hc;
}

int weight[maxn];
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF){
        HuffmanTree HT;
        for (int i = 0; i < n; ++i)
        {
            scanf("%d",&weight[i]);
        }
        
        createHuffmanTree(HT,n,weight);
        char ** HC;
        HC = HuffmanTreeCoding(HT,n);
        for (int i = 1; i <= n; ++i)
        {
            cout << HC[i] << endl;
        }
    
        delete(HC);
    }
    return 0;
}




















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值