Cod sursa(job #2886963)

Utilizator maria-marianita.cucos@s.unibuc.roCucos Marianita [email protected] Data 8 aprilie 2022 17:19:58
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include<bits/stdc++.h>

using namespace std;
const int N = 200001;

int v[N], h[N], poz[N], nh;

void Schimba(int a, int b){
    swap(h[a], h[b]);
    poz[h[a]] = a;
    poz[h[b]] = b;
}

void Urca(int p){
    while(p>1 && v[h[p]] < v[h[p/2]]){
        Schimba(p, p/2);
        p/=2;
    }
}

void Push(int x){
    h[++nh] = x;
    poz[x] = nh;
    Urca(nh);
}

void coboara(int p){
    int st=2*p, dr = 2*p+1, ok = p;
    if(st<=nh && v[h[st]] < v[h[ok]])
        ok=st;
    if(dr<=nh && v[h[dr]] < v[h[ok]])
        ok=dr;
    if(ok!=p){
        Schimba(p, ok);
        coboara(ok);
    }
}

void Delete(int p){
    if(p==nh){
        nh--;
    }
    else{
        h[p] = h[nh--];
        poz[h[p]] = p;
        Urca(p);
        coboara(p);
    }
}

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

int main(){
    int n, k=0;
    fin>>n;
    for(int i=0; i<n; i++){
        int op;
        fin>>op;
        if(op==1){
            fin>>v[++k];
            Push(k);
        }
        if(op==2){
            int p;
            fin>>p;
            Delete(poz[p]);
        }
        if(op==3){
            cout<<v[h[1]]<<'\n';
        }
    }
}