Cod sursa(job #3233952)

Utilizator addanciuAdriana Danciu addanciu Data 5 iunie 2024 16:08:20
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>

using namespace std;

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

const int N = 2e5;

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

int nh, nv;

int tata(int p){
    return (p - 1) / 2;
}

int fiu_stang(int p){
    return 2 * p + 1;
}

int fiu_drept(int p){
    return 2 * p + 2;
}

bool head_vid(int h[], int nh){
    return (nh == 0);
}

void schimba(int p1, int p2){
    swap(h[p1], h[p2]);
    poz[h[p1]] = p1;
    poz[h[p2]] = p2;
}

void urca(int p){
    while(p > 0 && v[h[p]] < v[h[tata(p)]]){
        schimba(p, tata(p));
        p = tata(p);
    }
}

void adauga(int poz_v){
    h[nh] = poz_v;
    poz[h[nh]] = nh;
    nh++;
    urca(nh - 1);
}

void coboara(int p){
    int fs = fiu_stang(p);
    int fd = fiu_drept(p);
    int optim = p;
    if(fs < nh && v[h[fs]] < v[h[optim]]){
        optim = fs;
    }
    if(fd < nh && v[h[fd]] < v[h[optim]]){
        optim = fd;
    }
    if(optim != p){
        schimba(optim, p);
        coboara(optim);
    }
}

void sterge(int p){
    if(p == nh - 1){
        nh--;
        return;
    }
    schimba(p, nh - 1);
    nh--;
    urca(p);
    coboara(p);

}

int main(){
    int nrop, tip;
    in >> nrop;
    nh = nv = 0;
    for(int i = 1; i <= nrop; i++){
        in >> tip;
        if(tip == 1){
            in >> v[nv++];
            adauga(nv - 1);
        }
        else if(tip == 2){
            int p;
            in >> p;
            p--;
            sterge(poz[p]);
        }
        else{
            out << v[h[0]] << '\n';
        }
    }
    return 0;
}