> 1); @classmethod def left(cls, i): 左兒子下標(biāo) return (i" />
class Heap(object):
@classmethod
def parent(cls, i):
"""父結(jié)點(diǎn)下標(biāo)"""
return int((i - 1) >> 1);
@classmethod
def left(cls, i):
"""左兒子下標(biāo)"""
return (i << 1) + 1;
@classmethod
def right(cls, i):
"""右兒子下標(biāo)"""
return (i << 1) + 2;
class MinPriorityQueue(list, Heap):
@classmethod
def min_heapify(cls, A, i, heap_size):
"""最小堆化A[i]為根的子樹"""
l, r = cls.left(i), cls.right(i)
if l < heap_size and A[l] < A[i]:
least = l
else:
least = i
if r < heap_size and A[r] < A[least]:
least = r
if least != i:
A[i], A[least] = A[least], A[i]
cls.min_heapify(A, least, heap_size)
def minimum(self):
"""返回最小元素,偽碼如下:
HEAP-MINIMUM(A)
1 return A[1]
T(n) = O(1)
"""
return self[0]
def extract_min(self):
"""去除并返回最小元素,偽碼如下:
HEAP-EXTRACT-MIN(A)
1 if heap-size[A] < 1
2 then error "heap underflow"
3 min ← A[1]
4 A[1] ← A[heap-size[A]] // 尾元素放到第一位
5 heap-size[A] ← heap-size[A] - 1 // 減小heap-size[A]
6 MIN-HEAPIFY(A, 1) // 保持最小堆性質(zhì)
7 return min
T(n) = θ(lgn)
"""
heap_size = len(self)
assert heap_size > 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] // 不是根結(jié)點(diǎn)且父結(jié)點(diǎn)更大時(shí)
5 do exchange A[i] ↔ A[PARENT(i)] // 交換兩元素
6 i ← PARENT(i) // 指向父結(jié)點(diǎn)位置
T(n) = θ(lgn)
"""
val = self[i]
assert key <= val, "new key is larger than current key"
self[i] = key
parent = self.parent
while i > 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 // 對(duì)元素個(gè)數(shù)增加
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))])
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com