Cod sursa(job #2152471)

Utilizator Andrei17Andrei Pascu Andrei17 Data 5 martie 2018 16:15:56
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>

using namespace std;

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

const int N = 200001;

int n, nh, h[N], poz[N], npoz, v[N];

inline void swapp(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 >> 1]]) {
        swapp(h[p], h[p >> 1]);
        p >>= 1;
    }
}

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) {
        swapp(h[p], h[bun]);
        coboara(bun);
    }
}

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

void sterge(int p) {
    swapp(h[p], h[nh--]);
    urca(p);
    coboara(p);
}

int main()
{
    int x, len;
    in >> len;
    for (int i = 1; i <= len; i++) {
        in >> x;
        if (x == 1) {
            in >> v[++n];
            adauga(n);
        }
        if (x == 2) {
            in >> x;
            sterge(x);
        }
        if (x == 3) out << v[h[1]] << '\n';
    }
    in.close();

    out.close();
}