已知字符及其权值,构造哈夫曼树,实现哈夫曼编码和解码过程。 【输入形式】 第一部分输入n个字符及其权值; 第二部分输入m个字符序列; 第三部分输入k个编码序列; 【输出形式】 输出每个字符序列对应的哈夫曼编码; 输出每个编码序列对应的字符序列; 【样例输入】 7 A,5 B,29 C,7 D,8 E,14 F,20 G,17 3 CEDFF ABCDEFG AAABBB 2 01111100100000 011001100110101010 【样例输出】 01111100100000 011010011101011000111 011001100110101010 CEDFF AAABBB 【样例说明】 【评分标准】 提交源文件的代码实现部分
时间: 2023-06-12 08:07:20 浏览: 119
以下是Python实现哈夫曼编码和解码的代码:
```python
class Node:
def __init__(self, freq, char=None):
self.freq = freq
self.char = char
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(freq_map):
nodes = [Node(freq, char) for char, freq in freq_map.items()]
while len(nodes) > 1:
nodes.sort()
left = nodes.pop(0)
right = nodes.pop(0)
parent = Node(left.freq + right.freq)
parent.left = left
parent.right = right
nodes.append(parent)
return nodes[0]
def build_huffman_codes(node, code_map, code=""):
if node.char is not None:
code_map[node.char] = code
else:
build_huffman_codes(node.left, code_map, code + "0")
build_huffman_codes(node.right, code_map, code + "1")
def encode(text, code_map):
return "".join(code_map[char] for char in text)
def decode(code, node):
text = ""
current_node = node
for bit in code:
if bit == "0":
current_node = current_node.left
else:
current_node = current_node.right
if current_node.char is not None:
text += current_node.char
current_node = node
return text
# 读取输入
n = int(input())
freq_map = {}
for i in range(n):
char, freq = input().split(",")
freq_map[char] = int(freq)
text = input().strip()
k = int(input())
codes = []
for i in range(k):
codes.append(input().strip())
# 构建哈夫曼树和编码
root = build_huffman_tree(freq_map)
code_map = {}
build_huffman_codes(root, code_map)
# 编码和解码
encoded_text = encode(text, code_map)
decoded_text = decode(encoded_text, root)
decoded_codes = [decode(code, root) for code in codes]
# 输出结果
print(encoded_text)
print(decoded_text)
print(" ".join(decoded_codes))
```
阅读全文