05_Priority Queues 优先队列
title: 05_Priority Queues 优先队列categories: 02_Silvertags:优先队列堆Priority QueueHeapPriority Queues 优先队列简介优先队列Priority Queue 或 Heap支持以下操作插入元素删除最高优先级元素获取最高优先级元素以上操作的时间复杂度均为O(log N)。优先队列比集合更简单更快应尽可能使用优先队列。Python 实现注意Python与 C 不同中删除和获取的是最小元素。heapq不是封装好的类而是直接操作传入的列表将其转换为堆。警告由于堆的结构特性打印 pq 不会按排序顺序打印元素而是直接打印列表。基本操作importheapq pq[]# 对于长度大于1的列表需要用 heapify 转换为堆heapq.heapify(pq)heapq.heappush(pq,7)# [7]heapq.heappush(pq,2)# [7, 2]heapq.heappush(pq,1)# [7, 2, 1]heapq.heappush(pq,5)# [7, 5, 2, 1]print(pq[0])# 1 获取最小元素heapq.heappop(pq)# 弹出最小值 [7, 5, 2]heapq.heappop(pq)# 弹出最小值 [7, 5]heapq.heappush(pq,6)# [7, 6, 5]常用方法方法说明heapq.heappush(pq, x)插入元素 xheapq.heappop(pq)弹出并返回最小值heapq.heapreplace(pq, x)弹出最小值并插入 x原子操作heapq.heapify(pq)将列表转换为堆大顶堆Python 的 heapq 只支持小顶堆。要实现大顶堆可以取负值# 大顶堆heapq.heappush(heap,-x)# 存入负值-x-heapq.heappop(heap)# 取出时取负例题Room AllocationCSES - Room Allocation问题描述给定 n 个客户的到达和离开时间求所需的最少房间数。思路按到达时间排序所有客户维护一个小顶堆存储已处理客户的离开时间对于每个客户如果堆顶的离开时间 新客户的到达时间说明有房间空出弹出堆顶并放入新客户的离开时间否则所有房间都满了需要分配新房间代码importheapqimportsys nint(sys.stdin.readline())timetable[]forcustomerinrange(n):arrival,departuremap(int,sys.stdin.readline().split())timetable.append((arrival,departure,customer))timetable.sort(keylambdax:x[0])# 按到达时间排序priority_queue[]# 存储 (离开时间, 客户编号)room_numbers[-1]*n# 房间分配结果forarrival,departure,customerintimetable:ifpriority_queueandarrivalpriority_queue[0][0]:# 有空房间room_numbers[customer]room_numbers[priority_queue[0][1]]heapq.heapreplace(priority_queue,(departure,customer))else:# 需要新房间heapq.heappush(priority_queue,(departure,customer))room_numbers[customer]len(priority_queue)print(len(priority_queue))print(*room_numbers)复杂度时间复杂度O(n log n)空间复杂度O(n)更多例题思路总结优先队列常用于贪心算法每次选择最小/最大的元素多路归并合并多个有序序列求 Top K维护最大的 K 个元素任务调度按优先级处理任务滑动窗口维护窗口内的最值
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2427793.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!