题解:B2168 【模板】哈夫曼编码

· · 题解

思路:

哈夫曼编码相信大家在CSP第一轮时都学过,构造过程就是选取两个权值最小的节点合并,新节点的权值为两者之和,直到只剩一个(感觉有点像合并果子)。用优先队列选取最小的两个节点,其他见代码吧!

代码:

#include<bits/stdc++.h>
#define int long long //防溢出
using namespace std;

struct Node
{
    string str,HuffmanCoding;//str:单词
    int weight,order,id,father,leftson,rightson;//weight:出现次数 order:叶子节点的初始输入顺序 id:节点编号 (其实father可以不用)
    bool operator< (const Node& x) const
    {
        return order<x.order;
    }//用来按顺序后排序输出
    bool operator> (const Node& x) const
    {
        return weight>x.weight;
    }//用来建小根堆
};

int n,size;
Node tree[2005];
priority_queue<Node,vector<Node>,greater<Node>> q;//小根堆

void dfs(string pre,int id)
{
    tree[id].HuffmanCoding=pre;
    if(tree[id].leftson!=-1) dfs(pre+'0',tree[id].leftson);
    if(tree[id].rightson!=-1) dfs(pre+'1',tree[id].rightson);
    return;
}//建完树后生成哈夫曼编码

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    cin>>n;
    if(n==1)
    {
        string str;
        cin>>str;
        cout<<str<<' '<<0<<'\n';
        return 0;
    }//n=1要特判,不然生成的是空字符串
    for(int i=0;i<n;i++)
    {
        tree[size].order=i;
        tree[size].id=size;
        cin>>tree[size].str>>tree[size].weight;
        tree[size].leftson=-1;
        tree[size].rightson=-1;
        q.push(tree[size]);
        size++;
    }
    while(q.size()>1)
    {
        int a,b;
        Node c;
        a=q.top().id;
        q.pop();
        b=q.top().id;
        q.pop();
        c.weight=tree[a].weight+tree[b].weight;
        c.order=0x3f3f3f3f;//将非叶子节点在最后排序时放到最后
        c.leftson=a;
        c.rightson=b;
        c.id=size;
        tree[a].father=c.id;
        tree[b].father=c.id;
        q.push(c);
        tree[size]=c;
        size++;
    }
    dfs("",q.top().id);
    sort(tree,tree+size);
    for(int i=0;i<n;i++)
    {
        cout<<tree[i].str<<' '<<tree[i].HuffmanCoding<<'\n';
    }
    return 0;
}