题解:P3378 【模板】堆

· · 题解

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e6+10;
int n,m,cnt; //cnt表示堆中节点个数 
int tr[N];
void insert(int x){
    tr[++cnt]=x;
    int now=cnt; //当前序号 
    while(now!=1){
        int fa=now/2; //父亲节点的序号 
        if(tr[fa]>tr[now]){ //与父亲比较 
            swap(tr[fa],tr[now]);
            now=fa;
        }else{
            break;
        }
    }
    return;
}
void del(){
    swap(tr[1],tr[cnt]);
    cnt--; //堆中节点个数减一 
    int now=1;
    while(now*2<=cnt){ //有子节点 
        int son=now*2;
        if(son+1<=cnt&&tr[son+1]<tr[son]){ //有两个儿子,比较哪个儿子小 
            son++;
        }
        if(tr[son]<tr[now]){ //与儿子比较 
            swap(tr[son],tr[now]);
            now=son;
        }else{
            break;
        }
    }
    return;
}
int main(){

    cin>>n;
    while(n--){
        int op,x;
        cin>>op;
        if(op==1){ //加入
            cin>>x;
            insert(x);
        }else if(op==2){ //输出 
            cout<<tr[1];
            puts("");
        }else if(op==3){ //删除 
            del();
        }
    }


    return 0;
}