Elias Gamma Code
Time limit1sMemory limit128 MB
Given counts of numbers by binary bit length, choose prefix shifts and optional leading zeros to minimize the total encoded length.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
The Elias gamma code is a code used to encode a sequence of positive integers. In this problem we use a modified version that can also encode .
An integer is encoded as follows.
- Let be the number of bits of written in binary. (The number of bits of is taken to be .)
- Write zeros, followed by a single . (This part is called the prefix.)
- Then write in binary.
The encodings of the numbers through are shown below.
To encode a sequence of integers, convert each number to its code as above and concatenate the codes in the order the numbers appear in the sequence.
When decoding a code back to the original number, the prefix in front of the binary representation is essential. While reading the encoded sequence, if you read zeros before reading a , it means the next bits are the encoded number.
To shorten the total length of the encoding, consider the following two optimizations.
- A prefix normally stands for a fixed bit count . If the sequence contains no number whose bit count is exactly , this prefix may instead be used to stand for numbers of bits. If a prefix already stands for bits, use it for bits, and so on, shifting up step by step. This shortens the prefix of those numbers.
- If you prepend a to every number whose bit count is , all of them become numbers of bits; you can then apply optimization 1. This is effective when there are very few numbers with bits but many numbers with more than bits.
We want to minimize the total length of the encoded sequence. The actual numbers of the sequence are not given; instead, the count of numbers whose bit count is is given as .
For example, consider , , , . (The sequence is one such case.) Without any optimization the length is 2×(1+1) + 4×(2+2) + 0×(3+3) + 1×(4+4) = 28. Using optimization 1, the prefix can be used for -bit numbers, saving bit. Using optimization 2, prepend a to the -bit numbers to make them -bit numbers. Applying optimization 1 again, using prefix for -bit numbers and prefix for -bit numbers, the length of the encoded string becomes 6×(1+2) + 1×(2+4) = 24.
Both optimizations may be applied multiple times. Write a program that finds the minimum length obtainable by combining the two methods appropriately.
Input
The input consists of several test cases. The first line of each test case contains an integer (). The second line contains values through , separated by spaces (). The input ends with a line containing , which should not be processed.
Output
For each test case, print on its own line the minimum possible Elias gamma encoding length for the given sequence.