Cod sursa(job #2757032)

Utilizator MoiseVictor123Moise victor MoiseVictor123 Data 3 iunie 2021 16:15:35
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>

using namespace std;

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

const int N = 2e5;

int nh = 0;
int v[N + 1], h[N + 1], poz[N + 1]; //poz = inversul lui h

void schimba(int x, int y) {
    swap(h[x], h[y]);
    poz[h[x]] = x;
    poz[h[y]] = y;
}

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

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

void coboara(int p) {
    int fs = 2 * p;
    int fd = 2 * p + 1;
    int 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) {
        schimba(p, bun);
        coboara(bun);
    }
}

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

int main() {
    int nop, n = 0;
    in >> nop;
    for(int i = 0; i < nop; i++) {
        int tip;
        in >> tip;
        if(tip == 1) {
            in >> v[++n];
            adauga(n);
        }
        if(tip == 2) {
            int p = 0;
            in >> p;
            sterge(poz[p]);
        }
        if(tip == 3) {
            out << v[h[1]] << "\n";
        }
    }
    in.close();
    out.close();
    return 0;
}