题解:B2168 哈夫曼编码

· · 题解

思路

考虑优先队列,每次选择权值最小的两个数,创造一个新的点,左右儿子分别指向这两个数,并放进优先队列。

统计编码时根据左右儿子深搜即可。

注意特判 n=1 的情况。

代码

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2005;
int n, k, x, y, xx, yy, l[N], r[N], a[N];
string s[N], ans[N];

struct note{
    int x, y;
    bool operator < (note _) const{
        return x > _.x;
    } 
};

priority_queue <note> q; 

void dfs(int x, string s){
    ans[x] = s;
    if(!l[x]) return ;
    dfs(l[x], s + "0"), dfs(r[x], s + "1");
}

signed main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i++) cin >> s[i] >> x, q.push({x, i});
    if(n == 1){
        cout << s[1] << " " << 0 << "\n";
        return 0;
    }
    k = n;
    while(1){
        x = q.top().x, y = q.top().y, q.pop();
        if(q.empty()) break; 
        xx = q.top().x, yy = q.top().y, q.pop();
        q.push({x + xx, ++k}), l[k] = y, r[k] = yy;
    }
    dfs(k, "");
    for(int i = 1; i <= n; i++) cout << s[i] << " " << ans[i] << "\n"; 
    return 0;
}