Tree interpretation
Lengths of a prefix code over an alphabet of size satisfy Kraft's inequality , and conversely every such integer length sequence can be realized. To see the converse, process lengths in increasing order, expanding each unused position into positions at the next depth and placing the required leaves.
Thus we seek a rooted tree with at most children per internal node, minimizing the sum of leaf weight times leaf depth. Zero-weight input elements remain real leaves and must not be discarded.
Huffman merging
If , output . Otherwise a full -ary tree has a leaf count congruent to modulo . Add
dummy leaves of weight zero. This preserves the optimum: remove unary nodes from an optimal tree, and consolidate incomplete internal nodes at the deepest level until only one incomplete node remains. Moving leaves toward the root cannot increase the cost for nonnegative weights. Filling its missing positions requires exactly these dummy leaves.
There is an optimal full tree whose lightest leaves are deepest siblings. Exchanging a lighter shallow leaf with a heavier deep leaf cannot increase cost. Contract these siblings into one leaf whose weight is their sum. The original cost equals the contracted cost plus that sum. Repeating this operation gives -ary Huffman coding.
Avoid constructing dummy leaves explicitly. Merge
real nodes first, and merge exactly nodes in every later step. In particular, gives . If is divisible by , the first merge must also use nodes.
Use a min-heap. Record the newly created node as the parent of each removed node. Parent indices are larger than child indices, so compute depths in reverse node order without recursion. Output the original leaves' depths in input order.
Bounds and complexity
There are at most internal nodes, each with at least two children. Thus every leaf depth is at most . Time is and space is .
A merged weight is at most . Assigning every leaf depth is feasible, so the optimum is at most . Signed 64-bit integers suffice; never compute directly.
Subtasks
For subtask 1, sort weights in decreasing order and enumerate nondecreasing depths from through . An exchange argument guarantees an optimum with this ordering. There are sequences, each checked in , giving time.
Subtask 2 is binary Huffman coding: repeatedly merge the two smallest weights in time.
Exact certificate checking
Count leaves at each depth. Start with one position at depth zero, subtract leaves placed there, and multiply remaining positions by before processing the next depth. Reject if a depth needs too many positions. Cap the position count at : there are only leaves, so larger exact counts cannot affect feasibility.
The checker recomputes the optimum and uses it as a remaining cost budget. Before subtracting , use division to detect an exceeded budget. This avoids overflow even for incorrect contestant output.
Solution written by GPT6