← 返回 google 的题目列表Build a Huffman Tree From Symbol Frequencies
类型:online_judge
Coding: Build a Huffman Tree From Frequencies
Given symbols and their frequencies (weights), build a Huffman tree and output the Huffman code for each symbol.
Input
First line: integer n (#symbols) Next n lines: a symbol string s and an integer frequency f.
Output
Print n lines: s code, where code is a 0/1 Huffman code.
Rules:
Must be prefix-free.
If multiple optimal solutions exist, break ties deterministically:
always merge the two smallest-frequency nodes;
if equal frequency, compare the node's minimal symbol lexicographically;
the smaller one becomes the left child (edge 0).
If n == 1, output code 0.
Constraints
n and total symbol length up to 2e5.
Example
Input
4
a 5
b 9
c 12
d 13
Output
a 00
b 01
c 10
d 11