复制代码 代码如下:
# -*- 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)
"""
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] // 不是根结点且父结点更大时
5 do exchange A[i] """
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 // 对元素个数增加
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))])
python,优先级队列
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]