Cod sursa(job #2417500)

Utilizator fremenFremen fremen Data 30 aprilie 2019 00:46:41
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <fstream>
#include <cstring>
#include <algorithm>
using namespace std;

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

const int MAXN = 200005;
int n;
int t;
int v[MAXN];
int poz[MAXN];
int c[MAXN];
int cr;

int parent(int k) {
    return k / 2;
}

int left(int k) {
    return k * 2;
}

int right(int k) {
    return k * 2 + 1;
}

void up(int k);

void add(int k) {
    v[++t] = k;
    poz[++cr] = t;
    c[t] = cr;
    up(t);
}

//poz - in ce nod se afla al k-lea el
//c - ce pozitie se afla in nod-ul k

void swapNode(int x, int y) {
    swap(v[x], v[y]);
    swap(c[x], c[y]);
    poz[c[x]] = x;
    poz[c[y]] = y;
}

void up(int k) {
    while (k > 1 && v[k] < v[parent(k)]) {
        swapNode(k, parent(k));
        k = parent(k);
    }
}

void down(int k) {
    int l = left(k);
    int r = right(k);
    int ok = 0;
    if (l <= t) {
        if (v[l] < v[k]) {
            ok += 1;
        }
    }
    if (r <= t) {
        if (v[r] < v[k]) {
            ok += 2;
        }
    }
    if (ok == 3) {
        if (v[l] < v[r]) {
            ok = 1;
        }
        else {
            ok = 2;
        }
    }
    if (ok == 1) {
        swapNode(k, l);
        down(l);
    }
    else if (ok == 2) {
        swapNode(k, r);
        down(r);
    }
}

void del(int k) {
    swapNode(k, t);
    t--;
    if (k > 1 && v[k] < v[parent(k)]) {
        up(k);
    }
    else {
        down(k);
    }
}

int main() {

    fin >> n;
    for (int i = 1; i <= n; ++i) {
        int k;
        fin >> k;
        if (k == 1) {
            int f;
            fin >> f;
            add(f);
        }
        else if (k == 2) {
            int f;
            fin >> f;
            del(poz[f]);
        }
        else {
            fout << v[1] << '\n';
        }
    }

    fout.close();
    return 0;
}