【AcWing】839.模拟堆

839.模拟堆

在这里插入图片描述

#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5+10;
int n,m=0;//m是操作次数,有多少个插入数
int h[N],ph[N],hp[N],cnt;//ph存储插入的第几个元素在堆上的第几个位置,hp存储堆的第几个元素存的是第几次插入的数
//交换a,b两个点,及其映射关系
void heap_swap(int a,int b){
    swap(ph[hp[a]],ph[hp[b]]);
    swap(hp[a],hp[b]);
    swap(h[a],h[b]);
}
void down(int u){
    int t=u;
    if(u*2<=cnt and h[u*2]<h[t])t=u*2;//左孩子
    if(u*2+1<=cnt and h[u*2+1]<h[t])t=u*2+1;//右孩子
    if(u!=t){
        heap_swap(u,t);
        down(t);
    }
}
void up(int u){
    while(u/2 and h[u/2]>h[u]){
        heap_swap(u/2,u);
        u/=2;
    }
}
int main(){
    cin>>n;
    while(n--){
        string op;
        int k,x;
        cin>>op;
        if(op=="I"){
            cin>>x;
            cnt++,m++;//初始化
            ph[m]=cnt;
            hp[cnt]=m;
            h[cnt]=x;
            up(cnt);
        }else if(op=="PM"){
            cout<<h[1]<<endl;
        }else if(op=="DM"){
            heap_swap(1,cnt);
            cnt--;
            down(1);
        }else if(op=="D"){
            cin>>k;
            k=ph[k];
            heap_swap(k,cnt);
            cnt--;
            down(k);
            up(k);
        }else{
            cin>>k>>x;
            k=ph[k];
            h[k]=x;
            down(k);
            up(k);
        }
    }
    return 0;
}

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值