class Node:
def __init__(self,freq):
self.left = None
self.right = None
self.father = None
self.freq = freq
def isLeft(self):
return self.father.left == self
#create nodes创建叶子节点
def createNodes(freqs):
return [Node(freq) for freq in freqs]
#create Huffman-Tree创建Huffman树
def createHuffmanTree(nodes):
queue = nodes[:]
while len(queue) > 1:
queue.sort(key=lambda item:item.freq)
node_left = queue.pop(0)
node_right = queue.pop(0)
node_father = Node(node_left.freq + node_right.freq)
node_father.left = node_left
node_father.right = node_right
node_left.father = node_father
node_right.father = node_father
queue.append(node_father)
queue[0].father = None
return queue[0]
#Huffman编码
def huffmanEncoding(nodes,root):
codes = [''] * len(nodes)
for i in range(len(nodes)):
node_tmp = nodes[i]
while node_tmp != root:
if node_tmp.isLeft():
codes[i] = '0' + codes[i]
else:
codes[i] = '1' + codes[i]
node_tmp = node_tmp.father
return codes
# 解压缩huffman文件
def decode_huffman(input_string, store, code_store):
encode = ''
decode = ''
for index in range(len(input_string)):
encode = encode + input_string[index]
for item in zip(store, code_store):
if encode == item[1]:
decode = decode + item[0][0]
encode = ''
return decode
if __name__ == '__main__':
# chars_freqs = [('C', 2), ('G', 2), ('E', 3), ('K', 3), ('B', 4),
# ('F', 4), ('I', 4), ('J', 4), ('D', 5), ('H', 6),
# ('N', 6), ('L', 7), ('M', 9), ('A', 10)]
# nodes = createNodes([item[1] for item in chars_freqs])
# root = createHuffmanTree(nodes)
# codes = huffmanEncoding(nodes,root)
# s = str(codes[0])
# for i in codes[1:]:
# s += ' ' + str(i)
# print(s)
q = int(input())
items_w = []
nodes =None
root = None
for i in range(q) :
x = input().split()
if int(x[0]) == 0:
for j in range(int(x[1])):
items_w.append([])
items_w[j].append(x[j+2])
for j in range(int(x[1])):
items_w[j].append(int(x[j+int(x[1])+2]))
nodes = createNodes([w[1] for w in items_w])
root = createHuffmanTree(nodes)
if int(x[0]) == 1:
codes = huffmanEncoding(nodes, root)
code_had = []
for j in x[1]:
for m in range(len(items_w)):
if items_w[m][0] == j:
code_had.append(codes[m])
s = str(code_had[0])
for i in code_had[1:]:
s += '' + str(i)
print(s)
if int(x[0])== 2:
codes = huffmanEncoding(nodes, root)
print(decode_huffman(x[1],items_w,codes))