QOJ.ac

QOJ

Limite de temps : 2 s Limite de mémoire : 256 MB Points totaux : 100 Difficulté: [afficher]

#495. 哈夫曼编码

Statistiques

Huffman 编码是最优前缀编码的一个著名家族。让我们简要回顾一下相关信息。

考虑包含 $n$ 个字符的字母表 $\Sigma$。该字母表的二进制前缀编码是一个映射 $c: \Sigma \to \{0, 1\}^*$,它为 $\Sigma$ 中的每个字符分配一个由 0 和 1 组成的字,使得对于任意 $u \neq v$,编码 $c(u)$ 都不是编码 $c(v)$ 的前缀。令编码 $c(a)$ 的长度记为 $|c(a)|$。给定文本 $t$ 以及字符 $a$ 在 $t$ 中的出现次数 $p(a)$,如果值 $\sum_{a \in \Sigma} |c(a)|p(a)$ 尽可能小,则该前缀编码对于 $t$ 是最优的。

Huffman 算法可以为给定的文本生成最优前缀编码。其过程如下:如果 $n=2$,则最优前缀编码显然是一个字符为 0,另一个为 1。设 $n > 2$。考虑两个分别具有最小 $p(x)$ 和 $p(y)$ 值的字符 $x$ 和 $y$。将这些字符合并为一个新字符 $z$,使得 $p(z) = p(x) + p(y)$。为得到的 $n-1$ 个字符的字母表构建最优前缀编码。现在,在 $z$ 的编码后附加 0 得到 $x$ 的编码,在 $z$ 的编码后附加 1 得到 $y$ 的编码。

例如,考虑文本 “abacaba”。我们有 $p(a) = 4$,$p(b) = 2$,$p(c) = 1$。合并 $b$ 和 $c$ 得到字符 $d$,使得 $p(a) = 4$,$p(d) = 3$。现在我们有 $c(a) = 0$ 和 $c(d) = 1$。回到 $b$ 和 $c$,我们有 $c(b) = 10$ 和 $c(c) = 11$。显然,Huffman 编码不是唯一的,因为我们在算法的每一步都可以自由交换 $x$ 和 $y$ 以获得另一个 Huffman 编码。在给定的例子中,另一个可能的 Huffman 编码是 $c(a) = 0$,$c(b) = 11$,$c(c) = 10$。

给定 $i$ 从 $1$ 到 $n$ 的整数 $u_i$ 和 $v_i$。请找出是否存在某个文本 $t$ 和某个 Huffman 编码,使得第 $i$ 个字符的编码恰好包含 $u_i$ 个 0 和 $v_i$ 个 1。如果存在这样的文本和编码,你需要打印出相应的 Huffman 编码。

输入格式

输入文件包含多个测试用例。 每个测试用例的第一行包含 $n$ ($2 \le n \le 100$)。接下来的 $n$ 行每行包含两个整数:$u_i$ 和 $v_i$ ($0 \le u_i, v_i \le 100, u_i + v_i > 0$)。 最后一个测试用例后跟一行包含零的行,该行不应被处理。

输出格式

对于每个测试用例,如果存在相应的文本 $t$,首先输出一行 “Yes”,否则输出 “No”。如果答案是肯定的,接下来的 $n$ 行必须包含编码,每行一个。编码必须由 0 和 1 组成,第 $i$ 行的打印编码必须包含 $u_i$ 个 0 和 $v_i$ 个 1,且打印的编码必须是某个 $n$ 字符字母表文本的 Huffman 编码。 如果有多个解,打印任意一个即可。

样例

输入 1

3
1 0
0 2
1 1
7
1 1
2 1
3 0
1 1
1 2
1 3
0 4
2
1 1
1 1
0

输出 1

Yes
0
11
10
Yes
10
001
000
01
110
1110
1111
No

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.