Huffman树模板(C++)

#include<bits/stdc++.h>
using namespace std;
struct Huffman{
    #define N 10000
    struct node{
        int id,l,r,val;
        char c;
        string code="";
        bool operator > (const node x)const{
            return -x.val>-val;
        }
    }p[N];
    int cnt=0,root=0,tot=0;
    priority_queue<node,vector<node>,greater<node> > Q;//建立小根堆 
    int vis[200],num[200];
    void Print(){//调试函数 
        for(int t=1;t<=cnt;t++){
            node x=p[t];
            cout<<"-----\n"<<x.c<<"\n"<<x.id<<'\n'<<x.l<<'\n'<<x.r<<'\n'<<x.val<<'\n';
            cout<<x.code<<'\n';
        }
        cout<<"\nroot="<<root;
    }
    void build(node a,node b){//建立Huffman树的新节点 
        ++cnt;p[cnt].id=cnt;
        p[cnt].val=a.val+b.val;
        p[cnt].l=a.val>b.val?b.id:a.id;
        p[cnt].r=a.val<=b.val?b.id:a.id;
        root=cnt;
    }
    void add(){//添加删除节点 
        node a=Q.top();Q.pop();
        node b=Q.top();Q.pop();
        build(a,b);Q.push(p[cnt]);
        tot--;
    }
    void newnode(char x,int times){//建立新节点 
        ++cnt;p[cnt].c=x;
        p[cnt].id=cnt;p[cnt].val=times;num[(int)x]=cnt;
        Q.push(p[cnt]);
    }
    void Forward(){while(tot-1)add();}//建立Huffman树 
    void sta(string a){
        memset(vis,0,sizeof(vis));
        for(int i=0;i<a.size();i++)vis[(int)a[i]]++;
        for(int i=0;i<200;i++)if(vis[i])tot++,newnode(char(i),vis[i]);
    }
    void make_code(int id){//构造Huffman编码 
        if(p[id].l)p[p[id].l].code=p[id].code+'0',make_code(p[id].l);
        if(p[id].r)p[p[id].r].code=p[id].code+'1',make_code(p[id].r);
    }
    string search(char x){//找字符的Huffman编码 
        return p[num[(int)x]].code;
    }
    string decode(string x){//对字符串解码 
        int len=x.size(),i=0;
        int now=root;string ans="";
        do{
            if(!p[now].l)ans+=p[now].c,now=root;
            now=x[i++]=='0'?p[now].l:p[now].r;
        }while(len!=i);
        if(!p[now].l)ans+=p[now].c,now=root;
        return ans;
    }
    void Make(string g){//初始化函数,可以直接调用这个初始化 
        sta(g);Forward();
    }
    string output_code(string g){//给定字符串输出其Huffman编码 
        string ans="";
        int len=g.size();
        for(int i=0;i<len;i++)ans+=p[num[g[i]]].code;
        return ans;
    }
};
int main(){//这是给的样例代码供参考,可以任意调用接口
    string g;cin>>g;
    Huffman T;
    T.Make(g);T.make_code(T.root);
    cout<<T.output_code(g)<<'\n';
    cout<<T.decode(T.output_code(g));
}

 5.6update 声明:这个代码用于二学位算法与设计的作业当中为ZYH所验证,不是抄袭

posted @ 2022-03-11 00:28  saionjisekai  阅读(53)  评论(0编辑  收藏  举报