跳到正文

题解

题解:B2168 哈夫曼编码

xuyifan2012约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年1月16日
收录
2026年2月4日
更新
2026年11月16日
篇幅
约 2 分钟
题目
B2168

版本

  1. v2当前
  2. v1

思路

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

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

注意特判 n=1n=1 的情况。

代码

C++
#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;
}
原文