Cod sursa(job #2153543)

Utilizator Andrei17Andrei Pascu Andrei17 Data 6 martie 2018 12:01:36
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>

using namespace std;

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

const int N = 200001;

int n, nheap;
int v[N], h[N], poz[N];

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

void coboara(int p) {
    int st = p << 1, dr = st + 1, bun = p;

    if (st <= nheap && v[h[st]] < v[h[bun]]) bun = st;
    if (dr <= nheap && v[h[dr]] < v[h[bun]]) bun = dr;

    if (bun != p) {
        myswap(p, bun);
        coboara(bun);
    }
}

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

void sterge(int p) {
    myswap(p, nheap--);
    urca(p);
    coboara(p);
}

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