Cod sursa(job #3124302)

Utilizator SergetecLefter Sergiu Sergetec Data 27 aprilie 2023 19:40:57
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
/*
 * Lefter Sergiu - 27/04/2023
*/
#include <fstream>

using namespace std;

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

const int N = 2e5;

int h[N + 1], v[N + 1], poz[N + 1], n, nh, nv;

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

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

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

void coboara(int p) {
    int fs = 2 * p, fd = 2 * p + 1, bun = p;
    if (fs <= nh && v[h[fs]] < v[h[bun]]) {
        bun = fs;
    }
    if (fd <= nh && v[h[fd]] < v[h[bun]]) {
        bun = fd;
    }
    if (bun != p) {
        schimb(bun, p);
        coboara(bun);
    }
}

void sterge(int p) {
    if (p != nh) {
        schimb(p, nh--);
        urca(p);
        coboara(p);
    } else {
        nh--;
    }
}

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