Huffman Encoding Total Length

VERY HARD · C · 5000ms

For efficient exam-result SMS broadcasts, Mitu wants to build a Huffman-style encoding of student names based on how often each is transmitted, minimizing total broadcast length. Given N characters with their frequencies, build a Huffman tree (always merge the two smallest-frequency nodes) and print the total encoded length in bits (sum of frequency × depth for each character).

Input

Line1: N. Line2: N frequencies.

Output

Total encoded length in bits.

Constraints

1 ≤ N ≤ 10^5

Sample Input

4
5 9 12 13

Sample Output

76
main.c
Loading editor…

Write C, then Run (custom I/O) or Submit (sample tests). ⌘/Ctrl+Enter submits.

Huffman Encoding Total Length · DIU ContestHub