代码如下:
# -*- coding: utf-8 -*-
class Heap(object):
@classmethod
def parent(cls, i):
"""父结点下标"""
return int((i - 1) >> 1);
@classmethod
def left(cls, i):
"""左儿子下标"""
return (i << 1) + 1;
@classmethod
def right(cls, i):
"""右儿子下标"""
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) // 保持最小堆性质
7 return min
T(n) = θ(lgn)
新闻热点
疑难解答