python计算最小优先级队列代码分享
本文导语: 代码如下:# -*- coding: utf-8 -*- class Heap(object): @classmethod def parent(cls, i): """父结点下标""" return int((i - 1) >> 1); @classmethod def left(cls, i): """左儿子下标""" return (i 0, "heap und...
# -*- coding: utf-8 -*-
class Heap(object):
@classmethod
def parent(cls, i):
"""父结点下标"""
return int((i - 1) >> 1);
@classmethod
def left(cls, i):
"""左儿子下标"""
return (i 0, "heap underflow"
val = self[0]
tail = heap_size - 1
self[0] = self[tail]
self.min_heapify(self, 0, tail)
self.pop(tail)
return val
def decrease_key(self, i, key):
"""将i处的值减少到key,伪码如下:
HEAP-DECREASE-KEY(A, i, key)
1 if key > A[i]
2 then error "new key is larger than current key"
3 A[i] ← key
4 while i > 1 and A[PARENT(i)] > A[i] // 不是根结点且父结点更大时
5 do exchange A[i] ↔ A[PARENT(i)] // 交换两元素
6 i ← PARENT(i) // 指向父结点位置
T(n) = θ(lgn)
"""
val = self[i]
assert key 0 and self[parent(i)] > self[i]:
self[i], self[parent(i)] = self[parent(i)], self[i]
i = parent(i)
def insert(self, key):
"""将key插入A,伪码如下:
MIN-HEAP-INSERT(A, key)
1 heap-size[A] ← heap-size[A] + 1 // 对元素个数增加
2 A[heap-size[A]] ← +∞ // 初始新增加元素为+∞
3 HEAP-DECREASE-KEY(A, heap-size[A], key) // 将新增元素减少到key
T(n) = θ(lgn)
"""
self.append(float('inf'))
self.decrease_key(len(self) - 1, key)
if __name__ == '__main__':
import random
keys = range(10)
random.shuffle(keys)
print(keys)
queue = MinPriorityQueue() # 插入方式建最小堆
for i in keys:
queue.insert(i)
print(queue)
print('*' * 30)
for i in range(len(queue)):
val = i % 3
if val == 0:
val = queue.extract_min() # 去除并返回最小元素
elif val == 1:
val = queue.minimum() # 返回最小元素
else:
val = queue[1] - 10
queue.decrease_key(1, val) # queue[1]减少10
print(queue, val)
print([queue.extract_min() for i in range(len(queue))])