Cod sursa(job #2939211)

Utilizator RaresPoinaruPoinaru-Rares-Aurel RaresPoinaru Data 13 noiembrie 2022 11:53:54
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");

const int MAXN=200010;

int h[MAXN],k,p[MAXN],v[MAXN],r;

inline int tata(int nod) {
    return nod/2;
}

inline int leftcopil(int nod) {
    return nod*2;
}

inline int rightcopil(int nod) {
    return nod*2+1;
}

inline void Urcare (int pos){
    while (pos>1 and v[h[pos]]<v[h[tata (pos)]]){
        swap(h[pos],h[tata(pos)]);
        swap(p[h[pos]],p[h[tata(pos)]]);
        pos=tata (pos);
    }
}

inline void Coborare (int pos){
    int copil=0;
    do {
        copil=0;
        if (leftcopil(pos)<=k) {
            copil=leftcopil(pos);
            if (rightcopil(pos)<=k and v[h[rightcopil(pos)]]<v[h[leftcopil(pos)]]) {
                copil=rightcopil (pos);
            }
            if (v[h[copil]]>=v[h[pos]]) {
               copil=0;
            }
        }
        if (copil){
            swap (h[pos],h[copil]);
            swap (p[h[pos]],p[h[copil]]);
            pos=copil;
        }

    }while (copil);
}

inline void Inserare (int x){
    v[++r]=x;
    k++;
    p[r]=k;
    h[k]=r;
    //fout <<h[k]<<'\n';
    Urcare (k);
}
inline void Eliminare (int pos){
    swap (h[pos],h[k]);
    swap(p[h[pos]],p[h[k]]);
    --k;
    if (pos>1 and v[h[pos]]<v[h[tata (pos)]])
        Urcare (pos);
    else
        Coborare (pos);
}

int main()
{
    int n;
    fin >>n;
    for (int i=1;i<=n;++i){
        int nr;
        fin >>nr;
        if (nr==1){
            int x;
            fin >>x;
            Inserare (x);
        }
        else{
            if (nr==2){
                int x;
                fin >>x;
                Eliminare (p[x]);
            }
            else
                fout <<v[h[1]]<<'\n';
        }
    }

    fin.close ();
    fout.close ();
    return 0;
}