Inverting Huffman
Time limit1sMemory limit128 MB
Given code lengths that some Huffman run can produce, find the smallest total character count that allows those lengths.
Problem
Static Huffman coding is an encoding algorithm used mainly for text compression. Given a text made of different characters, the algorithm chooses codes, one for each different character, and the text is compressed with those codes. To choose the codes, the algorithm builds a binary rooted tree having leaves. For the tree is built as follows.
- For each different character in the text build a tree containing just a single node, and assign to it a weight equal to the number of occurrences of the character within the text.
- Build a set containing the above trees.
- While contains more than one tree:
- Choose with minimum weight and remove it from .
- Choose with minimum weight and remove it from .
- Build a new tree with as its left subtree and as its right subtree, and assign to the sum of the weights of and .
- Include into .
- Return the only tree that remains in .
At steps 3.1 and 3.2 the set may contain several trees with minimum weight, so the text alone does not fix the shape of the tree. In the text abracadabra the character a occurs 5 times, b and r occur twice each, and c and d occur once each. One run of the algorithm gives code lengths 1, 2, 3, 4, 4 for a, b, r, c, d, and another run gives 1, 3, 3, 3, 3.
For each different character in the text, its code depends on the path that exists, in the final tree, from the root to the leaf corresponding to the character. The length of the code is the number of edges in that path, which is the same as the number of internal nodes in the path.
Given the lengths of the codes chosen by the algorithm, find the minimum size (total number of characters) that the text can have so that the generated codes have those lengths.
Input
The first line contains an integer , the number of different characters that appear in the text. ()
The second line contains integers , the lengths of the codes the algorithm chose for the different characters. (, )
At least one tree built as described above produces codes with the given lengths.
Output
Print one line with an integer, the minimum size (total number of characters) that the text can have so that the generated codes have the given lengths.