>1); ; 更新日期:2024/11/27,互联网资源,高清电影,韩剧美剧,动漫资讯,游戏教程,序列号,破解版,注册机,绿色版,教程网,王者荣耀,SEO教程,网络教程,运营推广,下载中心,破解软件,游戏软件,网站源码,易语言源码,安卓软件,QQ软件,汉化版,无损音乐,MKV,WAV+CUE,FLAC,HQCD,MP3,SACD,DSD,抖音,4K高清,320k,度盘,百度云盘,蓝奏,微云盘,网盘,无广告纯净版,不限速下载,去广告,VIP解析,8" />
脚本专栏 
首页 > 脚本专栏 > 浏览文章

python计算最大优先级队列实例

(编辑:jimmy 日期: 2024/11/27 浏览:3 次 )

复制代码 代码如下:
# -*- 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)
        """
        heap_size = len(self)
        assert heap_size > 0, "heap underflow"
        val = self[0]
        tail = heap_size - 1
        self[0] = self[tail]
        self.max_heapify(self, 0, tail)
        self.pop(tail)
        return val

    def increase_key(self, i, key):
        """将i处的值增加到key,伪码如下:
        HEAP-INCREASE-KEY(A, i, key)
        1  if key < A[i]
        2    the error "new key is smaller 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 smaller 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,伪码如下:
        MAX-HEAP-INSERT(A, key)
        1  heap-size[A] ← heap-size[A] + 1 // 对元素个数增加
        2  A[heap-size[A]] ← -∞ // 初始新增加元素为-∞
        3  HEAP-INCREASE-KEY(A, heap-size[A], key) // 将新增元素增加到key

        T(n) = θ(lgn)
        """
        self.append(float('-inf'))
        self.increase_key(len(self) - 1, key)

if __name__ == '__main__':
    import random

    keys = range(10)
    random.shuffle(keys)
    print(keys)

    queue = MaxPriorityQueue() # 插入方式建最大堆
    for i in keys:
        queue.insert(i)
    print(queue)

    print('*' * 30)

    for i in range(len(keys)):
        val = i % 3
        if val == 0:
            val = queue.extract_max() # 去除并返回最大元素
        elif val == 1:
            val = queue.maximum() # 返回最大元素
        else:
            val = queue[1] + 10
            queue.increase_key(1, val) # queue[1]增加10
        print(queue, val)

    print([queue.extract_max() for i in range(len(queue))])

上一篇:python算法学习之桶排序算法实例(分块排序)
下一篇:python计算最小优先级队列代码分享
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap