小根堆的插入与删除

本文介绍了一种使用C++实现的小根堆数据结构,并展示了如何通过该结构进行元素的插入(push)、获取最小值及删除最小值(pop)等操作。通过对代码的详细解析,帮助读者理解小根堆的基本原理及其在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
const int Maxn=1000005;
int sta[Maxn];
int n,tot=0;//tot记录元素总数,记得及时更新
inline int read() {
    int x=0,w=1;
    char ch=0;
    while(ch!='-' && (ch<'0' || ch>'9')) ch=getchar();
    if(ch=='-') w=-1,ch=getchar();
    while(ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*w;
}
inline void push(int b) {
    sta[++tot]=b;
    for(int i=tot,j=i>>1; j; i=j,j=i>>1) {
        if(sta[j]>sta[i]) swap(sta[j],sta[i]);
        //只需要判断当前节点与父亲的大小关系
    }
}
inline void pop() {
    sta[1]=sta[tot--];//最小值覆盖掉
    for(int i=1,j=i<<1; j<=tot; i=j,j=i<<1) {
        if(j+1<=tot&&sta[j+1]<sta[j]) j++;//因为是小根堆,所以在两个兄弟节点之间选取更小的那个向上推
        if(sta[i]<sta[j]) break;//此时没有交换的必要
        else swap(sta[i],sta[j]);
 
    }
}
int main() {
    n=read();
    int a,b;
    for(int i=1; i<=n; i++) {
        a=read();
        if(a==1) {
            b=read();
            push(b);
        } else if(a==2) printf("%d\n",sta[1]);
        else if(a==3) pop();
    }
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值