Python 优先队列:heapq库的使用

2024-02-04 09:50

本文主要是介绍Python 优先队列:heapq库的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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


本文目录

    • 简介
    • 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 ( n log ⁡ k ) O(n \log k) O(nlogk),其中 n n n 是所有序列的元素个数, k k k 是序列的个数。函数返回一个已排序值的迭代器,可以使用 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 函数是一个基于堆的通用功能函数,用于返回最大的 n n n 个元素,时间复杂度为 O ( n log ⁡ k ) O(n \log k) O(nlogk),其中 n n n 是序列的长度, k k k 是要返回的元素个数。如果 n n n 小于 k k k,则返回整个序列。

函数原型如下:

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 函数在 n n n 值较小时性能较好。对于较大的 n n n,使用 sorted(iterable, reverse=True)[:n] 性能更好。当 n = 1 n=1 n=1 时,使用 max(iterable) 函数性能更好。

nsmallest

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

函数原型如下:

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 函数在 n n n 值较小时性能较好。对于较大的 n n n,使用 sorted(iterable)[:n] 性能更好。当 n = 1 n=1 n=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 n n n and t t t.

There is a deck of n n n 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 t t t ( 1 ≤ t ≤ 1 0 4 1 \le t \le 10^4 1t104) — the number of test cases in the test.

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

The second line of each test case contains n n n integers s 1 , s 2 , … , s n s_1, s_2, \dots, s_n s1,s2,,sn ( 0 ≤ s i ≤ 1 0 9 0 \le s_i \le 10^9 0si109) — card powers in top-down order.

It is guaranteed that the sum of n n n over all test cases does not exceed 2 ⋅ 1 0 5 2 \cdot 10^5 2105.

Output

Output t t t 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 1 1 1 and 2 2 2. Both hero cards will receive 3 3 3 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 2 2 2 and 3 3 3 bonuses and get 6 6 6 total power.

In the fourth sample, you can take bonuses 1 1 1, 2 2 2, 3 3 3, 5 5 5 and skip the bonus 6 6 6, then the hero 4 4 4 will be enhanced with a bonus 3 3 3 by 5 5 5, and the hero 7 7 7 with a bonus 5 5 5 by 4 4 4. 4 + 5 = 9 4+5=9 4+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)

这篇关于Python 优先队列:heapq库的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/677084

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

hdu1180(广搜+优先队列)

此题要求最少到达目标点T的最短时间,所以我选择了广度优先搜索,并且要用到优先队列。 另外此题注意点较多,比如说可以在某个点停留,我wa了好多两次,就是因为忽略了这一点,然后参考了大神的思想,然后经过反复修改才AC的 这是我的代码 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]