#-*-Coding:utf-8-*-
Class Heap (object):
@classmethod
def parent (CLS, i):
"" "Parent node Subscript" "
return int ((i-1) >> 1);
@classmethod
Def left (CLS, i):
"" "" "The Left son subscript" "
Return (I << 1) + 1;
@classmethod
def right (CLS, i):
"" "the Right son subscript" "
Return (I << 1) + 2;
Class Minpriorityqueue (list, Heap):
@classmethod
def min_heapify (CLS, A, I, heap_size):
"" Minimum heap a[i] is the root subtree "" "
l, r = Cls.left (i) , Cls.right (i)
if L < heap_size and a[l] < A[i]:
& nbsp; 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):
"" returns the smallest element, the pseudo code is as follows:
Heap-minimum (A)
1 return a[1]
T (n) = O (1)
"""
return self[0]
def extract_min (self):
"" To remove and return the smallest element, the pseudo code is as follows:
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]]//tail element to first
5 Heap-size[a]←heap-size[a]-1//decrease Heap-size[a]
6 min-heapify (A, 1)//Keep the minimum heap properties
7 return min
T (n) =θ (LGN)
""
heap_size = Len (self)
Assert heap_size > 0, "Heap underflow"
val = self[0]
& nbsp; 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):
"" To reduce the value of I to key, The pseudo code is as follows:
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
&nbs p; 4 While I > 1 and a[parent (i)] > A[i]//is not a root node and the parent node is larger
& nbsp; 5 do Exchange a[i]↔a[parent (i)]//Exchange two element
6 i←parent (i)//point to parent node location
T (n) =θ (LGN)
""
val = self[i]
assert key <= Val, "New key is larger than current key"
self[i] = key
&nbs p; 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):
"" To insert a key, the pseudo code is as follows:
Min-heap-insert (A, key)
1 Heap-size[a]←heap-size[a] + 1//Increased number of elements
2 a[heap-size[a]]←+∞//Initial new addition element is +∞
3 Heap-decrease-key (A, Heap-size[a], key)//reduce new elements to 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 () # Insert method Build Minimum heap
For i in the keys:
Queue.insert (i)
Print (queue)
Print (' * ' * 30)
For I in range (len (queue)):
val = i% 3
If val = 0:
val = queue.extract_min () # Remove and return the smallest element
Elif val = = 1:
val = queue.minimum () # returns the smallest element
Else
val = queue[1]-10
Queue.decrease_key (1, Val) # Queue[1] reduced by 10
Print (queue, Val)
Print ([Queue.extract_min () for I in range (len (queue))]