QOJ.ac

QOJ

Limite de temps : 1 s Limite de mémoire : 128 MB Points totaux : 100

#3119. Elias gamma 编码

Statistiques

Elias gamma 编码是一种简单的编码方式,可用于对正整数序列进行编码。我们将使用一种改进的编码方式,它也能够对零进行编码。要对整数 $n$ 进行编码,请执行以下操作:

  1. 令 $k$ 为 $n$ 的二进制位数。
  2. 写下 $k-1$ 个零,后跟一个 $1$。
  3. 写下 $n$ 的二进制表示。

样例

数值 二进制 位数 前缀 编码
0 0 1 1 10
1 1 1 1 11
2 10 2 1 110
3 11 2 1 111
4 100 3 1 1100
5 101 3 1 1101
6 110 3 1 1110
7 111 3 1 1111
8 1000 4 1 11000

整数序列的编码方式是将序列中各个整数的编码按其在序列中出现的顺序依次写出。在每个整数的二进制表示之前,需要 $k$ 位的前缀来解码编码后的整数。因此,在读取整数序列的编码时,如果我们读到 $k-1$ 个零后跟一个 $1$,这意味着后面紧跟的 $k$ 位是下一个编码整数的二进制表示。

如果我们想要缩短整数序列的编码长度,仍有改进空间;我们将考虑以下两种优化:

  1. 如果存在一个前缀表示后面紧跟 $k$ 位,但序列中没有 $k$ 位的整数,我们可以使用该前缀来表示后面紧跟 $k+1$ 位。如果已经存在一个表示后面紧跟 $k+1$ 位的前缀,则该前缀不再需要,可以将其用于表示后面紧跟 $k+2$ 位,依此类推。
  2. 我们可以为序列中所有 $k$ 位的整数的二进制表示添加一个前导零,使其变为 $k+1$ 位的整数,然后可以使用第一种优化。如果 $k$ 位的整数很少,而位数超过 $k$ 的整数很多,这种优化似乎特别有用。

在最小化整数序列的编码长度时,我们只关心序列中有多少个整数具有特定的位数。令 $c_i$ 表示序列中具有 $i$ 位的整数个数。

让我们看下面的例子:$c_1 = 2, c_2 = 4, c_3 = 0, c_4 = 1$(例如,这可能对应于序列 2, 1, 3, 8, 0, 2, 3)。使用原始的 Elias gamma 编码,序列的编码长度为 $2 × (1 + 1) + 4 × (2 + 2) + 0 × (3 + 3) + 1 × (4 + 4) = 28$。通过使用优化 1,我们可以使用前缀 001 来表示 4 位的整数,从而节省 1 位。然后,我们可以使用优化 2,为 1 位的整数添加前导零,使其占用 2 位。接着,我们使用优化 1,为 2 位的整数使用前缀 1,为 4 位的整数使用前缀 01,得到新的长度为 $6 × (1 + 2) + 1 × (2 + 4) = 24$。

这两种优化都可以多次使用。注意,对于第二种优化,很难决定何时以及如何使用它。目标是以最佳方式结合这两种优化,这意味着我们要找到给定整数序列的一种编码,使其在所有使用 Elias gamma 编码并结合这两种优化的编码中长度最小。

输入格式

输入文件包含多个测试用例。每个测试用例的第一行包含一个整数 $n$ ($1 ≤ n ≤ 128$)。下一行包含数值 $c_1, \cdots, c_n$ ($0 ≤ c_i ≤ 10000$)。输入以 $n=0$ 结束。

输出格式

对于每个测试用例,输出一行,表示给定输入序列编码后的最小长度。

样例

输入格式 1

4
2 4 0 1
5
9 4 2 4 3
11
44 56 96 26 73 80 77 50 33 16 78
0

输出格式 1

24
99
5494

说明

第一个样例测试用例对应于题目描述中给出的例子。

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.