哈夫曼树--贪心算法

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

#define N 10    // 带编码字符的个数,即树中叶结点的最大个数
#define M 19    // 树中总的结点数目

class HTNode{   // 树中结点的结构
public:
    unsigned int weight;
    unsigned int parent,lchild,rchild;
};

class HTCode{
public:
    char data;      // 待编码的字符
    int weight;     // 字符的权值
    char code[N];   // 字符的编码
};

void Init(HTCode hc[], int *n){// 初始化,读入待编码字符的个数n,从键盘输入n个字符和n个权值
    cout<<"输入字符个数"<<endl;
    cin>>*n;
    cout<<"输入字符"<<endl;
    for(int i = 1; i <= *n; ++i)
        cin >> hc[i].data;
    cout << "输入权值" << endl;
    
    for(int i = 1; i <= *n; ++i)
        cin >> hc[i].weight;
}

void Select(HTNode ht[], int k, int *s1, int *s2){// ht[1...k]中选择parent为0,并且weight最小的两个结点,其序号由指针变量s1,s2指示
    int i;
    for(i=1; i<=k && ht[i].parent != 0; ++i);
    *s1 = i;
    for(i=1; i<=k; ++i){
        if(ht[i].parent==0 && ht[i].weight<=ht[*s1].weight)
            *s1 = i;
    }//找到最小的节点
    for(i=1; i<=k; ++i){
        if(ht[i].parent==0 && i!=*s1)
            break;
    }
    *s2 = i;
    for(i=1; i<=k; ++i){
        if(ht[i].parent==0 && i!=*s1 && ht[i].weight<=ht[*s2].weight)
            *s2 = i;
    }
}
void HuffmanCoding(HTNode ht[],HTCode hc[],int n){// 构造Huffman树ht,并求出n个字符的编码
    char cd[N];
    int m,c,f,s1,s2,start;
    m = 2*n-1;
    for(int i=1; i<=m; ++i){
        if(i <= n)
            ht[i].weight = hc[i].weight;
        else
            ht[i].parent = 0;
        ht[i].parent = ht[i].lchild = ht[i].rchild = 0;
    }
    for(int i=n+1; i<=m; ++i){
        Select(ht, i-1, &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;
    }
    cd[n-1] = '\0';
    for(int i=1; i<=n; ++i){
        start = n-1;
        for(c=i,f=ht[i].parent; f; c=f,f=ht[f].parent){
            if(ht[f].lchild == c)//左为0,右为1
                cd[--start] = '0';
            else
                cd[--start] = '1';
        }
        strcpy(hc[i].code, &cd[start]);
    }
}

int main()
{
    int i,n;
    HTNode ht[M+1];
    HTCode hc[N+1];
    Init(hc, &n);     // 初始化
    HuffmanCoding(ht,hc,n);   // 构造Huffman树,并形成字符的编码
    for(i=1; i<=n; ++i)
        cout<<hc[i].data<<"---"<<hc[i].code<<endl;
    cout<<endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值