AcWing 148. 合并果子
原题链接
简单
作者:
皓首不倦
,
2020-09-05 22:26:09
,
所有人可见
,
阅读 413
'''
利用Huffman树求解最小的路径长度和及节点权值乘积和
'''
class HuffmanTreeNode:
def __init__(self, val, left = None, right = None):
self.val = val
self.left = left
self.right = right
def __cmp__(self, other):
return self.val - other.val
def __lt__(self, other):
return self.val < other.val
from queue import PriorityQueue
class HuffmanTree:
def __init__(self):
self.root = None
# 贪心算法构建Huffman树
def build(self, val_list):
if self.root is not None:
return
if len(val_list) == 0:
return
min_heap = PriorityQueue()
for val in val_list:
min_heap.put(HuffmanTreeNode(val))
while min_heap.qsize() > 1:
node1 = min_heap.get()
node2 = min_heap.get()
min_heap.put(HuffmanTreeNode(node1.val + node2.val, node1, node2))
self.root = min_heap.get()
# 获取带权路径和
def getMinWeightedSum(self):
def dfs(root, level):
if root is None:
return 0
if root.left is None and root.right is None:
return root.val * level
return dfs(root.left, level+1) + dfs(root.right, level+1)
return dfs(self.root, 0)
# 获取每一个数值的编码
def getCodes(self):
m = {}
def dfs(root, path, flag):
if root is None:
return
path.append('' if flag is None else flag)
if root.left is None and root.right is None:
m[root.val] = ''.join(path)
path.pop(-1)
return
dfs(root.left, path, '0')
dfs(root.right, path, '1')
dfs(self.root, [], None)
return m
n = int(input())
arr = list(map(int, input().split()))
tree = HuffmanTree()
tree.build(arr)
print(tree.getMinWeightedSum())