堆的常用方法
使用list表示一个堆
将无序List转换成最小堆;heapq.heapify(a)
最小堆a中添加元素x:heapq.heappush(a, x)
弹出并返回最小元素:heapq.heappop(a)
弹出并返回最小元素,同时添加元素x:heapq.heapreplace(a,x)
?
import heapq
a = [11, 6, 9, 8, 7, 3]
heapq.heapify(a)
print(a)
heapq.heappush(a, 4)
print(a)
heapq.heappush(a, 12)
print(a)
while len(a):
print(heapq.heappop(a), end=' ')
#
[3, 6, 9, 8, 7, 11]
[3, 6, 4, 8, 7, 11, 9]
[3, 6, 4, 8, 7, 11, 9, 12]
3 4 6 7 8 9 11 12