代码如下:
# -*- 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 MaxPriorityQueue(list, Heap):
@classmethod
def max_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]:
largest = l
else:
largest = i
if r < heap_size and A[r] > A[largest]:
largest = r
if largest != i:
A[i], A[largest] = A[largest], A[i]
cls.max_heapify(A, largest, heap_size)
def maximum(self):
"""返回最大元素,伪码如下:
HEAP-MAXIMUM(S)
1 return A[1]
T(n) = O(1)
"""
return self[0]
def extract_max(self):
"""去除并返回最大元素,伪码如下:
HEAP-EXTRACT-MAX(A)
1 if heap-size[A] < 1
2 then error "heap underflow"
3 max ← A[1]
4 A[1] ← A[heap-size[A]] // 尾元素放到第一位
5 heap-size[A] ← heap-size[A] - 1 // 减小heap-size[A]
6 MAX-HEAPIFY(A, 1) // 保持最大堆性质
7 return max
T(n) = θ(lgn)
新闻热点
疑难解答