0
点赞
收藏
分享

微信扫一扫

acwing模拟堆

niboac 2022-01-14 阅读 25
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;

const int N=100010;


int h[N],ph[N],hp[N],size1;//ph[k]存的是第k个插入点在堆内下标,hp[k]是堆内第k个结点是第几个插入的点

void head_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<=size1 && h[u*2]<h[t]) t=u*2;
    if(u*2+1<=size1 && h[u*2+1]<h[t]) t=u*2+1;
    if(u!=t){
        head_swap(t,u);
        down(t);
    }
}

void up(int u){
    while(u/2 && h[u/2]>h[u])
        {
        head_swap(u/2,u);
        u/=2;
    }
}

int main()
{
    int n,m=0;
    char op[10];
    scanf("%d",&n);
    while(n--){
        
        scanf("%s",op);
        int k,x;
        if(!strcmp(op,"I")){
            scanf("%d ",&x);
            size1 ++;
            m ++;
            ph[m]=size1,hp[size1]=m;
            h[size1]=x;
            up(size1);
        }
        else if(!strcmp(op,"PM")) printf("%d\n",h[1]);
        else if(!strcmp(op,"DM")){
            head_swap(1,size1);
            size1--;
            down(1);
        }
        else if(!strcmp(op,"D")){
            scanf("%d",&k);
            k=ph[k];
            head_swap(k,size1);
            size1 --;
            down(k),up(k);
        }
        else{
            scanf("%d%d",&k,&x);
            k=ph[k];
            h[k]=x;
            down(k),up(k);
        }
    }
    return 0;
}


举报

相关推荐

Acwing---839. 模拟堆

模拟堆(堆)

acwing 828 模拟栈

839. 模拟堆

栈:AcWing 828. 模拟栈

0 条评论