Cod sursa(job #2836737)

Utilizator CaptnBananaPetcu Tudor CaptnBanana Data 20 ianuarie 2022 20:24:22
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>

using namespace std;

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

const int N = 2e5 + 1;
int n, op, val, h;
int poz[N], crono[N], timp; // crono - timp in functie de pozitie, poz - pozitie in functie de timp
int heap[N];

void interschimba(int a, int b){
    swap(heap[a], heap[b]);
    swap(crono[a], crono[b]);
    poz[crono[a]] = a;
    poz[crono[b]] = b;
}

void urca(int p){
    while(heap[p] < heap[p / 2]){
        interschimba(p, p / 2);
        p /= 2;
    }
}

void coboara(int p){
    int bun = p;
    if(2 * p <= h && heap[2 * p] < heap[bun])
        bun = 2 * p;

    if(2 * p + 1 <= h && heap[2 * p + 1] < heap[bun])
        bun = 2 * p + 1;

    if(bun != p){
        interschimba(p, bun);
        coboara(bun);
    }
}

void minim(){
    g << heap[1] << '\n';
}

void insereaza(int val){
    heap[++h] = val;
    crono[h] = ++timp;
    poz[timp] = h;
    urca(h);
}

void sterge(int cronp){
    int p = poz[cronp];
    if(p == h){
        h--;
        return;
    }

    interschimba(p, h--);
    if(heap[p] < heap[p / 2])
        urca(p);
    else
        coboara(p);
}

int main(){
    f >> n;
    while(n--){
        f >> op;
        if(op == 1){
            f >> val;
            insereaza(val);
        }else if(op == 2){
            f >> val;
            sterge(val);
        }else
            minim();
    }

    f.close();
    g.close();
}