模板代码——哈夫曼编码

· · 算法·理论

#include<bits/stdc++.h>
#define ll long long
#define rep(i,x,y) for(int i=x;i<=y;i++)
using namespace std;
const int N=1e3+5;

int n;
struct node
{
    string name;
    int id,fa,l,r;
    ll w;
    bool operator<(const node &cmp)const
    {
        return w>cmp.w||w==cmp.w&&id>cmp.id;
    }
}tr[N<<1];
priority_queue<node> pq;
void build_tr()
{
    rep(i,1,n) pq.push(tr[i]);
    int idx=n;
    while(pq.size()>1)//贪心构造哈夫曼树 
    {
        node t1=pq.top();
        pq.pop();
        node t2=pq.top();
        pq.pop();
    tr[++idx].id=idx;
        tr[idx].w=t1.w+t2.w;
        tr[t1.id].fa=tr[t2.id].fa=tr[idx].id;
        tr[idx].l=t1.id,tr[idx].r=t2.id;
        pq.push(tr[idx]);
    }
}
string search(int x)//输出每个叶子结点的哈夫曼编码 
{
    string ret;
    int fa=tr[x].fa;
    if(fa==0) return "";
    if(tr[fa].l==x) ret=search(fa)+'0';
    else ret=search(fa)+'1';
    return ret;
}
int main()
{
    cin>>n;
    rep(i,1,n) cin>>tr[i].name>>tr[i].w,tr[i].id=i;
    if(n==1)//节点数为1时那一个节点的哈夫曼编码为0或1 
    {
        cout<<tr[1].name<<" 0"<<endl;
        return 0;
    }
    build_tr();
    rep(i,1,n) cout<<tr[i].name<<" "<<search(i)<<endl;
    return 0;
}