Cod sursa(job #2544788)

Utilizator minecraft3Vintila Valentin Ioan minecraft3 Data 12 februarie 2020 15:27:00
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

int v[200005], poz[200005], h[200005], nh, nv;

void heap_swap(int p, int q) {
    swap(h[p], h[q]);
    poz[h[p]] = p;
    poz[h[q]] = q;
}

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

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

void add(int p) { // p = pozitie
    h[++nh] = p;
    poz[p] = nh;
    urca(nh);
}

void remove(int p) {
    heap_swap(p, nh--);
    urca(p); coboara(p);
}

int main() {
    // v[i] = al i-lea citit (valoarea)
    // h[i] = al catelea citit se afla pe pozitia i in heap
    // poz[i] = pozitia din heap al celui de-al i-lea citit

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

    int n, x;
    fin >> n; do {
        fin >> x;
        if(x == 1) {
            fin >> v[++nv];
            add(nv);
        } else if(x == 2) {
            fin >> x;
            remove(poz[x]);
        } else {
            fout << v[h[1]] << '\n';
        }
    } while(--n);
    return 0;
}