Cod sursa(job #2567974)

Utilizator luci.tosaTosa Lucian luci.tosa Data 3 martie 2020 19:57:57
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
#define NMAX 200005
using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int a[NMAX],h[NMAX],pos[NMAX];
int n,order,op;
int father(int node) {
    return node/2;
}
int ls(int node) {
    return 2*node;
}
int rs(int node) {
    return 2*node+1;
}
void change(int p,int q) {
    swap(h[p],h[q]);
    pos[h[p]]=p;
    pos[h[q]]=q;
}
void up(int k) {
    while(k>1 && a[h[k]] < a[h[father(k)]]) {
        change(k,father(k));
        k=father(k);
    }
}
void down(int k) {
    int son=0;
    if(ls(k)<=n) {
        son=ls(k);
        if(rs(k)<=n && a[h[rs(k)]] < a[h[ls(k)]])
            son=rs(k);
        if(a[h[son]] >= a[h[k]])
            son=0;
    }
    if(son) {
        change(k,son);
        down(son);
    }
}
void ins(int x) {
    h[++n]=x;
    pos[x]=n;
    up(n);
}

void del(int k) {
    change(k,n);
    n--;
    up(k);
    down(k);
}
int main() {
    fin>>op;
    for(int i=1; i<=op; i++) {
        int p,x;
        fin>>p;
        if(p==3)
            fout<<a[h[1]]<<"\n";
        else {
            fin>>x;
            if(p==1) {
                a[++order]=x;
                ins(order);
            } else
                del(pos[x]);
        }
    }
    return 0;
}