Under construction

Still being built. Things may change

K-ary Huffman Encoding

Interview

Time limit1sMemory limit1024 MB

Summary
Given N character frequencies, find the minimum total length of a K-ary prefix-free encoding of the weighted string.
Level

Medium5 of 10

Topics
Greedy, Heap
Solved
No attempts yet

Input

The Huffman language has NN characters. Unlike Korea, which uses binary encoding made of 0 and 1, the Huffman language uses KK-ary encoding made of the digits 00 through K−1K - 1.

We want to encode the Huffman language in KK-ary. The encoding must satisfy the following conditions.

  1. Assign one KK-ary string to each of the NN characters.
  2. No assigned string may be a prefix of another assigned string.

For example, the table below shows a valid 33-ary encoding of the four characters !, @, #, and +.

CharacterEncoding
!012
@120
#201
+210

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 33 and is not valid in base 33.

CharacterEncoding
!013
@120
#201
+210

The table after that breaks the second condition, because + is a prefix of #.

CharacterEncoding
!012
@120
#201
+20

Given a string in the Huffman language, what is the shortest possible length of its KK-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 5454 (3×3+4×3+5×3+6×3=543 \times 3 + 4 \times 3 + 5 \times 3 + 6 \times 3 = 54).

Output

The input contains TT test cases. The first line contains TT.

The first line of each test case contains two integers NN (2≤N≤10 0002 \le N \le 10\,000) and KK (2≤K≤10 0002 \le K \le 10\,000), separated by a space. NN is the number of characters in the Huffman language, and KK is the base to encode in. The next line contains NN integers CiC_i (0≤Ci≤100 0000 \le C_i \le 100\,000), separated by spaces. Each CiC_i is the number of times the ii-th character appears in the string.

Hint

For each test case, print on its own line the minimum possible length of the KK-ary encoding of the given string.

Problem

In both test cases, assigning the following encoding gives the minimum length.

CharacterEncoding
30
210
1110
0111

In the first case, the string can be expressed with length 3+4+3=103 + 4 + 3 = 10. In the second case, it can be expressed with length 3+4+2=93 + 4 + 2 = 9.

Examples1

  1. Example 1

    Input
    2
    4 2
    0 1 2 3
    4 2
    0 1 2 2
    
    Expected output
    10
    9