哈夫曼编码

#include<bits/stdc++.h>
using namespace std;
struct node{//树结构体
    int w;//权重(即该字符在文本中出现的次数)
    node *l; node *r;//左右子树
    bool is;//是否是叶子节点
    char c;//字符
};
struct cmp{
    bool operator ()(node *a,node *b){
        return a->w > b->w;
    }
};
void setValue(node* &tmp, int _w, node* a, node *b, bool _is, char _c) {//赋值函数
    tmp->w = _w;  tmp->l = a;  tmp->r = b;  tmp->is = _is;  tmp->c = _c;
}
void fu(node *n,string ss){//dfs输出哈夫曼编码
    if(n->is) {cout<<n->c<<"的出现次数为"<<n->w<<","<<" 哈夫曼编码为"<<ss<<""<<endl;return;}//如果是叶子节点就输出字符以及编码
    if(n->l) fu(n->l,ss+"0");//如果有左子树,继续递归搜索左子树,同时要传入更新过的哈夫曼编码
    if(n->r) fu(n->r,ss+"1");//如果有右子树,继续递归搜索右子树,同时要传入更新过的哈夫曼编码
    return;
}
int main(){
    string s; printf("请输入你的文本\n"); cin>>s;
    string ss="";
    map<char, int> ma;//每个字符和他的权重(即该字符在文本中出现的次数)
    priority_queue<node *,vector<node*>,cmp >qu;//优先队列便于给各个节点按照权重大小排序
    map<char,int>::iterator it;//迭代器
    int num = 0;//最小带权路径长度初始化为0
    for(int i = 0; i < s.length(); i++){
        if(ma.count(s[i])) ma[s[i]]++;//如果出现过,则对应的次数加一
        else ma[s[i] ] = 1;//如果没有出现过,次数为1
    }
    for(it = ma.begin(); it != ma.end(); it++){
        node *h = (node*)malloc(sizeof(node));
        setValue(h, it->second,NULL,NULL,true,it->first);
        qu.push(h);//加入优先队列
    }
    while(qu.size()>1){//当优先队列中的元素多于一个的时候
        int n1 = (qu.top())->w;//n1赋值为最小的权重
        node *h1 = qu.top();//h1指向权重最小的节点
        qu.pop();//将该节点弹出
        int n2 = (qu.top())->w;//n2赋值为第二小的权重(第一小的在上一行被弹出了)
        node *h2 = qu.top();//h2指向权重第二小的节点
        qu.pop();//将该节点弹出
        int tmp = n1+n2;//目前带权路径长度为n1+n2
        node *n3 = (node*)malloc(sizeof(node*));
        setValue(n3,tmp,h1,h2,false,0);//新建根节点
        qu.push(n3);//加入优先队列
        num+=tmp;
    }
    node*n3 = qu.top();
    printf("最小带权路径长度为%d\n",num);
    fu(n3,ss);
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值