python实现堆(最大堆、最小堆、最小最大堆)

2023-04-04 19:30:41 来源:腾讯云


【资料图】

1. 最大堆

class MaxHeap:    def __init__(self):        self.heap = []    def parent(self, i):        return (i - 1) // 2    def left_child(self, i):        return 2 * i + 1    def right_child(self, i):        return 2 * i + 2    def get_max(self):        if not self.heap:            return None        return self.heap[0]    def insert(self, item):        self.heap.append(item)        self._heapify_up(len(self.heap) - 1)    def extract_max(self):        if not self.heap:            return None        max_item = self.heap[0]        last_item = self.heap.pop()        if self.heap:            self.heap[0] = last_item            self._heapify_down(0)        return max_item    def _heapify_up(self, i):        while i > 0 and self.heap[i] > self.heap[self.parent(i)]:            self.heap[i], self.heap[self.parent(i)] = self.heap[self.parent(i)], self.heap[i]            i = self.parent(i)    def _heapify_down(self, i):        max_index = i        left = self.left_child(i)        if left < len(self.heap) and self.heap[left] > self.heap[max_index]:            max_index = left        right = self.right_child(i)        if right < len(self.heap) and self.heap[right] > self.heap[max_index]:            max_index = right        if i != max_index:            self.heap[i], self.heap[max_index] = self.heap[max_index], self.heap[i]            self._heapify_down(max_index)if __name__ == "__main__":    max_heap = MaxHeap()    max_heap.insert(1)    max_heap.insert(2)    max_heap.insert(0)    max_heap.insert(8)    print(max_heap.get_max())

2. 最小堆

class MinHeap:    def __init__(self):        self.heap = []    def parent(self, i):        return (i - 1) // 2    def left_child(self, i):        return 2 * i + 1    def right_child(self, i):        return 2 * i + 2    def get_min(self):        if not self.heap:            return None        return self.heap[0]    def insert(self, item):        self.heap.append(item)        self._heapify_up(len(self.heap) - 1)    def extract_min(self):        if not self.heap:            return None        min_item = self.heap[0]        last_item = self.heap.pop()        if self.heap:            self.heap[0] = last_item            self._heapify_down(0)        return min_item    def _heapify_up(self, i):        while i > 0 and self.heap[i] < self.heap[self.parent(i)]:            self.heap[i], self.heap[self.parent(i)] = self.heap[self.parent(i)], self.heap[i]            i = self.parent(i)    def _heapify_down(self, i):        min_index = i        left = self.left_child(i)        if left < len(self.heap) and self.heap[left] < self.heap[min_index]:            min_index = left        right = self.right_child(i)        if right < len(self.heap) and self.heap[right] < self.heap[min_index]:            min_index = right        if i != min_index:            self.heap[i], self.heap[min_index] = self.heap[min_index], self.heap[i]            self._heapify_down(min_index)

3. 最小-最大堆

最小-最大堆的性质是:树中偶数层的每个节点都小于它的所有后代,而树中奇数层的每个节点都大于它的所有后代。

用途 双端优先级队列

class MinMaxHeap:    def __init__(self):        self.heap = []    def parent(self, i):        return (i - 1) // 2    def left_child(self, i):        return 2 * i + 1    def right_child(self, i):        return 2 * i + 2    def get_min(self):        if not self.heap:            return None        return self.heap[0]    def get_max(self):        if not self.heap:            return None        if len(self.heap) == 1:            return self.heap[0]        if len(self.heap) == 2:            return self.heap[1] if self.heap[1] > self.heap[0] else self.heap[0]        return self.heap[1] if self.heap[1] > self.heap[2] else self.heap[2]    def insert(self, item):        self.heap.append(item)        self._heapify_up(len(self.heap) - 1)    def extract_min(self):        if not self.heap:            return None        min_item = self.heap[0]        last_item = self.heap.pop()        if self.heap:            self.heap[0] = last_item            self._heapify_down_min(0)        return min_item    def extract_max(self):        if not self.heap:            return None        max_item = self.get_max()        max_index = self.heap.index(max_item)        self.heap[max_index] = self.heap[-1]        self.heap.pop()        if max_index < len(self.heap):            self._heapify_down_max(max_index)        return max_item    def _heapify_up(self, i):        if i == 0:            return        parent = self.parent(i)        if self.heap[i] < self.heap[parent]:            self.heap[i], self.heap[parent] = self.heap[parent], self.heap[i]            self._heapify_up_max(parent)        else:            self._heapify_up_min(i)    def _heapify_up_min(self, i):        grandparent = self.parent(self.parent(i))        if i > 2 and self.heap[i] < self.heap[grandparent]:            self.heap[i], self.heap[grandparent] = self.heap[grandparent], self.heap[i]            self._heapify_up_min(grandparent)    def _heapify_up_max(self, i):        grandparent = self.parent(self.parent(i))        if i > 2 and self.heap[i] > self.heap[grandparent]:            self.heap[i], self.heap[grandparent] = self.heap[grandparent], self.heap[i]            self._heapify_up_max(grandparent)    def _heapify_down_min(self, i):        while True:            min_index = i            left = self.left_child(i)            if left < len(self.heap) and self.heap[left] < self.heap[min_index]:                min_index = left            right = self.right_child(i)            if right < len(self.heap) and self.heap[right] < self.heap[min_index]:                min_index = right            if i != min_index:                self.heap[i], self.heap[min_index] = self.heap[min_index], self.heap[i]                i = min_index            else:                break    def _heapify_down_max(self, i):        while True:            max_index = i            left = self.left_child(i)            if left < len(self.heap) and self.heap[left] > self.heap[max_index]:                max_index = left            right = self.right_child(i)            if right < len(self.heap) and self.heap[right] > self.heap[max_index]:                max_index = right            if i != max_index:                self.heap[i], self.heap[max_index] = self.heap[max_index], self.heap[i]                i = max_index            else:                break

在这个实现中,MinMaxHeap类代表一个min-max堆,包含一个list堆,用于存放堆中的元素。 parent、left_child 和right_child 方法分别返回节点的父节点、左子节点和右子节点的索引。 get_min 方法返回堆中的最小元素,get_max 方法返回堆中的最大元素。 insert 方法将一个元素插入到堆中并维护堆属性。 extract_min 方法从堆中移除最小元素并保持堆属性。 extract_max 方法从堆中移除最大元素并保持堆属性。

_heapify_up、_heapify_up_min、_heapify_up_max、_heapify_down_min 和 _heapify_down_max 方法用于维护最小-最大堆属性。 _heapify_up 在向堆中插入元素后调用,以确保元素位于正确的位置。 _heapify_up_min 和 _heapify_up_max 由 _heapify_up 调用以维护最小-最大堆属性。 _heapify_down_min 和 _heapify_down_max 分别被 extract_min 和 extract_max 调用,以维护 min-max 堆属性。

标签

郴州安仁文旅项目集中开工 总投资1000万元

3月16日,安仁县举行文旅项目集中开工活动,县委书记王洪灿在开工仪式上宣布:湘南起义旧址群——朱毛井...

2022-03-20 15:40:46

2022年郴州计划重点推进文旅项目101个 总投资354亿元

3月16日,我市举行全市文旅项目和城市大提质大融城项目集中开工仪式,市委书记吴巨培宣布项目开工。郴州...

2022-03-20 15:39:41

宿州泗县深入推进文旅融合发展 擦亮城市品牌

近年来,泗县以争创安徽省文化旅游名县为目标,深入推进文旅融合发展,努力擦亮水韵泗州 运河名城城市...

2022-03-20 15:38:59

汽车零部件产业“领头羊” 锦州力争一季度“开门红”

3月16日,记者从锦州汽车零部件产业的领头羊——锦州万得集团获悉,今年前两个月,企业订单充足,正铆足...

2022-03-20 15:37:41

油价或有望冲击“九元”大关 宁波新能源汽车市场如何

新一轮国内成品油调价窗口于3月17日24时开启,油价或有望冲击九元大关。前一天晚上11点,鄞州区不少加油...

2022-03-20 15:34:38

从水塘到“云”端 全国最大高邮鸭养殖基地实现智慧养殖

随着新一代数字技术的蓬勃发展,以新兴技术推动现代化新农村建设正成为助力乡村振兴的重要手段。1个人能...

2022-03-20 15:33:17

淡季不忘引流 京郊民宿市场有望迎来回暖

旅游淡季中的京郊民宿有望成为市场中最先复苏的板块。3月17日,北京商报记者调查发现,虽然正值旅游淡季...

2022-03-20 15:32:01

镇江乡村一二三产业融合发展 闯出“镇江之路”

从烹饪江鲜河豚的个体小饭店到规模化的江岛乡村旅游产业集群,从白兔草莓丁庄葡萄的单个农户种植到茅山...

2022-03-20 15:31:11

总投资30亿元 盐城东台8个重大产业项目相继开工

总投资30亿元的精密电子元器件项目、同益电子项目,总投资10亿元的金利美精密组件项目、天永智能设备项...

2022-03-20 15:30:13

去年南京规上信息软件业企业实现营收7577.28亿元 同比增长10.3%

市统计局最新统计数据显示,2021年,我市规模以上信息软件业企业共1662家,较上年同期增加321家,实现营...

2022-03-20 15:28:57
x 广告
x 广告

Copyright  2015-2022 太平洋粮油网版权所有  备案号:豫ICP备2022016495号-17   联系邮箱:93 96 74 66 9@qq.com