K-ary Huffman Encoding
InterviewTime limit1sMemory limit1024 MB
Given N character frequencies, find the minimum total length of a K-ary prefix-free encoding of the weighted string.
Input
The Huffman language has characters. Unlike Korea, which uses binary encoding made of 0 and 1, the Huffman language uses -ary encoding made of the digits through .
We want to encode the Huffman language in -ary. The encoding must satisfy the following conditions.
- Assign one -ary string to each of the characters.
- No assigned string may be a prefix of another assigned string.
For example, the table below shows a valid -ary encoding of the four characters !, @, #, and +.
No string in this table is a prefix of another, so both conditions hold. The next table breaks the first condition, because ! is assigned 013, which uses the digit and is not valid in base .
The table after that breaks the second condition, because + is a prefix of #.
Given a string in the Huffman language, what is the shortest possible length of its -ary encoding? For example, suppose the string !!!@@@@#####++++++ contains ! 3 times, @ 4 times, # 5 times, and + 6 times. With the first encoding table above, the total length is ().
Output
The input contains test cases. The first line contains .
The first line of each test case contains two integers () and (), separated by a space. is the number of characters in the Huffman language, and is the base to encode in. The next line contains integers (), separated by spaces. Each is the number of times the -th character appears in the string.
Hint
For each test case, print on its own line the minimum possible length of the -ary encoding of the given string.
Problem
In both test cases, assigning the following encoding gives the minimum length.
In the first case, the string can be expressed with length . In the second case, it can be expressed with length .