Python 优先队列:heapq库的使用
创始人
2025-05-28 09:43:17
0

✅作者简介:人工智能专业本科在读,喜欢计算机与编程,写博客记录自己的学习历程。
🍎个人主页:小嗷犬的个人主页
🍊个人网站:小嗷犬的技术小站
🥭个人信条:为天地立心,为生民立命,为往圣继绝学,为万世开太平。


本文目录

  • 简介
  • heapq 库的使用
    • heapify
    • heappush
    • heappop
    • heapreplace
    • heappushpop
    • merge
    • nlargest
    • nsmallest
  • 例题
    • Title
      • Time Limit
      • Memory Limit
      • Problem Description
      • Input
      • Output
      • Sample Input
      • Sample Onput
      • Note
      • Source
      • Solution


简介

heapq 库是 Python 标准库中的一部分,它提供了一些堆操作的函数,可以用来实现优先队列。

优先队列是一种特殊的队列,它的每个元素都有一个优先级,元素的出队顺序是按照优先级从高到低的顺序进行的。优先队列的实现有多种方式,其中最常用的是堆。

堆是一种特殊的树,有两种类型,分别是最大堆和最小堆。最大堆的每个节点的值都大于或等于其子节点的值,最小堆的每个节点的值都小于或等于其子节点的值。堆的根节点是堆中的最大值(最小堆的根节点是最小值)。

heapq 的大部分操作都是基于最小堆实现的,通过将元素取相反数,可以实现最大堆。


heapq 库的使用

heapq 库提供了 heapifyheappushheappopheapreplaceheappushpopmergenlargestnsmallest 等函数,用于堆的操作。

heapify

heapify 函数用于原地将列表转换为最小堆,时间复杂度为 O(n)O(n)O(n)。

函数原型如下:

heapq.heapify(x)

其中,x 是一个列表。

示例:

import heapq
x = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(x)
print(x)
# [0, 1, 2, 6, 3, 5, 4, 7, 8, 9]

heappush

heappush 函数用于将元素插入到最小堆中,并保持堆的不变性,时间复杂度为 O(log⁡n)O(\log n)O(logn)。

函数原型如下:

heapq.heappush(heap, item)

其中,heap 是一个最小堆,item 是要插入的元素。

示例:

import heapq
x = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(x)
heapq.heappush(x, 2.5)
print(x)
# [0, 1, 2, 6, 2.5, 5, 4, 7, 8, 9, 3]

heappop

heappop 函数用于弹出最小堆的根节点,并保持堆的不变性,时间复杂度为 O(log⁡n)O(\log n)O(logn)。如果堆为空,则抛出 IndexError 异常。

函数原型如下:

heapq.heappop(heap)

其中,heap 是一个最小堆。

示例:

import heapq
x = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(x)
print(heapq.heappop(x))
# 0
print(x)
# [1, 3, 2, 6, 9, 5, 4, 7, 8]

使用 heap[0] 可以访问最小堆的根节点,但是不会弹出它。

import heapq
x = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(x)
print(x[0])
# 0
print(x)
# [0, 1, 2, 6, 3, 5, 4, 7, 8, 9]

heapreplace

heapreplace 函数用于弹出最小堆的根节点,并将新元素插入到堆中,保持堆的大小和不变性,时间复杂度为 O(log⁡n)O(\log n)O(logn)。如果堆为空,则抛出 IndexError 异常。它比先调用 heappop 再调用 heappush 效率更高。

函数原型如下:

heapq.heapreplace(heap, item)

其中,heap 是一个最小堆,item 是要插入的元素。

示例:

import heapq
x = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(x)
heapq.heapreplace(x, -1)
print(x)
# [-1, 1, 2, 6, 3, 5, 4, 7, 8, 9]

heappushpop

heappushpop 函数用于将元素插入到最小堆中,并弹出最小堆的根节点,保持堆的大小和不变性,时间复杂度为 O(log⁡n)O(\log n)O(logn)。如果堆为空,则抛出 IndexError 异常。它比先调用 heappush 再调用 heappop 效率更高。

函数原型如下:

heapq.heappushpop(heap, item)

其中,heap 是一个最小堆,item 是要插入的元素。

示例:

import heapq
x = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(x)
heapq.heappushpop(x, -1)
print(x)
# [0, 1, 2, 6, 3, 5, 4, 7, 8, 9]

merge

merge 函数是一个基于堆的通用功能函数,用于合并多个有序的序列,返回一个新的有序的序列,时间复杂度为 O(nlog⁡k)O(n \log k)O(nlogk),其中 nnn 是所有序列的元素个数,kkk 是序列的个数。函数返回一个已排序值的迭代器,可以使用 list 函数将其转换为列表。

函数原型如下:

heapq.merge(*iterables, key=None, reverse=False)

其中,iterables 是多个有序的序列,key 是一个函数,用于从序列中提取比较的键,reverse 是一个布尔值,表示是否反转序列。

示例:

import heapq
x = [1, 3, 5, 7, 9]
y = [2, 4, 6, 8, 10]
z = heapq.merge(x, y)
print(list(z))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

nlargest

nlargest 函数是一个基于堆的通用功能函数,用于返回最大的 nnn 个元素,时间复杂度为 O(nlog⁡k)O(n \log k)O(nlogk),其中 nnn 是序列的长度,kkk 是要返回的元素个数。如果 nnn 小于 kkk,则返回整个序列。

函数原型如下:

heapq.nlargest(n, iterable, key=None)

其中,n 是要返回的元素个数,iterable 是一个序列,key 是一个函数,用于从序列中提取比较的键。

示例:

import heapq
x = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
print(heapq.nlargest(3, x))
# [9, 8, 7]

nlargest 函数在 nnn 值较小时性能较好。对于较大的 nnn,使用 sorted(iterable, reverse=True)[:n] 性能更好。当 n=1n=1n=1 时,使用 max(iterable) 函数性能更好。

nsmallest

nsmallest 函数是一个基于堆的通用功能函数,用于返回最小的 nnn 个元素,时间复杂度为 O(nlog⁡k)O(n \log k)O(nlogk),其中 nnn 是序列的长度,kkk 是要返回的元素个数。如果 nnn 小于 kkk,则返回整个序列。

函数原型如下:

heapq.nsmallest(n, iterable, key=None)

其中,n 是要返回的元素个数,iterable 是一个序列,key 是一个函数,用于从序列中提取比较的键。

示例:

import heapq
x = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
print(heapq.nsmallest(3, x))
# [0, 1, 2]

nsmallest 函数在 nnn 值较小时性能较好。对于较大的 nnn,使用 sorted(iterable)[:n] 性能更好。当 n=1n=1n=1 时,使用 min(iterable) 函数性能更好。


例题

Title

CodeForces 1800 C2. Powering the Hero (hard version)

Time Limit

2 seconds

Memory Limit

256 megabytes

Problem Description

This is a hard version of the problem. It differs from the easy one only by constraints on nnn and ttt.

There is a deck of nnn cards, each of which is characterized by its power. There are two types of cards:

You can do the following with the deck:

Your task is to use such actions to gather an army with the maximum possible total power.

Input

The first line of input data contains single integer ttt (1≤t≤1041 \le t \le 10^41≤t≤104) — the number of test cases in the test.

The first line of each test case contains one integer nnn (1≤n≤2⋅1051 \le n \le 2 \cdot 10^51≤n≤2⋅105) — the number of cards in the deck.

The second line of each test case contains nnn integers s1,s2,…,sns_1, s_2, \dots, s_ns1​,s2​,…,sn​ (0≤si≤1090 \le s_i \le 10^90≤si​≤109) — card powers in top-down order.

It is guaranteed that the sum of nnn over all test cases does not exceed 2⋅1052 \cdot 10^52⋅105.

Output

Output ttt numbers, each of which is the answer to the corresponding test case — the maximum possible total power of the army that can be achieved.

Sample Input

5
5
3 3 3 0 0
6
0 3 3 0 0 3
7
1 2 3 0 4 5 0
7
1 2 5 0 4 3 0
5
3 1 0 0 4

Sample Onput

6
6
8
9
4

Note

In the first sample, you can take bonuses 111 and 222. Both hero cards will receive 333 power. If you take all the bonuses, one of them will remain unused.

In the second sample, the hero’s card on top of the deck cannot be powered up, and the rest can be powered up with 222 and 333 bonuses and get 666 total power.

In the fourth sample, you can take bonuses 111, 222, 333, 555 and skip the bonus 666, then the hero 444 will be enhanced with a bonus 333 by 555, and the hero 777 with a bonus 555 by 444. 4+5=94+5=94+5=9.

Source

CodeForces 1800 C2. Powering the Hero (hard version)

Solution

每张英雄牌的最大力量为该英雄牌之前出现的未被使用最大奖励牌的力量。对于具体是哪张英雄牌使用了哪张奖励牌,我们是不关心的,只需要统计他们最大力量即可。

import heapqfor _ in range(int(input())):n = int(input())s = map(int, input().split())h = []ans = 0for i in s:if i == 0 and h:ans -= heapq.heappop(h)else:heapq.heappush(h, -i)print(ans)

相关内容

热门资讯

华为手机适合安卓系统,安卓生态... 你有没有发现,最近华为手机在安卓系统圈子里可是风头无两呢?这不,我就来给你好好捋一捋,为什么华为手机...
安卓系统下载福建助学,安卓系统... 你有没有听说最近安卓系统上有个超级棒的福建助学项目?没错,就是那个能让你轻松下载各种学习资源的神器!...
i7安卓系统,引领智能科技新潮... 你有没有想过,手机和电脑的结合体是什么样的呢?想象一个既能流畅运行大型游戏,又能轻松处理日常办公的设...
安卓改鸿蒙系统安装,系统升级安... 你有没有想过给你的安卓手机换换口味呢?没错,就是那种焕然一新的感觉!今天,就让我来带你一起探索如何将...
安卓原生系统美化软件,个性化美... 你有没有发现,安卓手机用久了,界面总是有点单调乏味呢?别急,今天就来给你安利几款超好用的安卓原生系统...
安卓系统图案解锁方法,安卓系统... 手机解锁,这可是每天都要经历的小环节,是不是觉得有点儿单调呢?今天,就让我来带你一起探索一下安卓系统...
安卓系统怎么调俄语,安卓系统设... 你有没有想过,在安卓手机上轻松切换到俄语界面呢?这可不是什么高难度的任务,只要跟着我一步步来,保证让...
安卓系统怎么配置内网,安卓系统... 你有没有想过,家里的安卓设备怎么才能轻松连接到内网呢?这可是个实用的小技巧哦!想象你可以在手机上直接...
安卓系统更新 文件路径,安卓系... 你有没有发现,你的安卓手机最近是不是总在提醒你更新系统呢?每次更新,都感觉手机焕然一新,功能更强大了...
wish只能用安卓系统,探索无... 你知道吗?在手机世界里,有一个神奇的愿望清单,只有安卓系统的小伙伴们才能实现哦! 今天,就让我带你一...
开元安卓车机系统,智能驾驶新体... 你有没有发现,现在的汽车越来越智能了?这不,最近我入手了一辆配备了开元安卓车机系统的车,简直让我爱不...
安卓系统旁白怎么关,如何关闭安... 你是不是也和我一样,在使用安卓手机的时候,不小心开启了旁白功能,现在想把它关掉,却怎么也找不到方法?...
安卓手机系统流畅版,极致性能与... 你有没有发现,最近你的安卓手机用起来是不是特别顺滑?没错,就是那种点屏幕就立刻响应的感觉,简直让人爱...
forest安卓系统换到苹果,... 你有没有想过,手机操作系统就像是我们生活中的不同道路,有时候,你可能觉得一条路走得太久了,想要换一条...
华为鸿蒙系统安卓平板,开启智能... 亲爱的读者们,你是否也像我一样,对科技圈的新鲜事儿充满好奇?今天,我要和你聊聊一个最近在科技圈掀起波...
安卓系统藏族软件下载,精选安卓... 安卓系统藏族软件下载:探索藏族文化的数字新篇章在数字化时代,手机已经成为我们生活中不可或缺的一部分。...
显示安卓系统耗电大,深度剖析原... 手机电量总是不够用?是不是觉得安卓系统耗电特别大?别急,今天就来给你揭秘安卓系统耗电的秘密,让你手机...
抽取原装安卓系统驱动,深度挖掘... 你有没有遇到过这种情况?手机里的安卓系统突然卡顿,或者某个应用突然罢工,这时候你是不是想给它来个“大...
安卓系统手机游戏排行,热门游戏... 你有没有发现,最近你的手机里是不是又多了一款游戏?没错,安卓系统手机游戏排行又更新了!今天,就让我带...
安卓系统叫AR 特效,安卓系统... 你知道吗?最近在安卓系统上出现了一个超级酷炫的新功能,它就是AR特效!是不是听起来就让人兴奋不已?那...