Cod sursa(job #1616001)

Utilizator Vali_DeaconuVali Deaconu Vali_Deaconu Data 27 februarie 2016 00:40:36
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
# include <fstream>
# include <algorithm>

using namespace std;

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

const int MAXH = 200010;
int heap[MAXH], val[MAXH], pos[MAXH];
int vsize, hsize;

void push(int x) {
    int i = x, j = (x>>1);
    while (j) {

        if (val[heap[i]] >= val[heap[j]]) // tata >= fiu
            break;

        swap(heap[j], heap[i]);

        pos[heap[j]] = j;
        pos[heap[i]] = i;

        i = j;
        j = (i>>1);
    }
}

void pop(int x) {
    int i = x, j = (x<<1);
    while (j <= hsize) {
        if (j < hsize && val[heap[j + 1]] <= val[heap[j]]) // fiu stanga <= fiu dreapta
            ++j;

        if (val[heap[i]] <= val[heap[j]]) // nu mai e necesar shiftul
            break;

        swap(heap[i], heap[j]);

        pos[heap[i]] = i;
        pos[heap[j]] = j;

        i = j;
        j = (i<<1);
    }
}

int main() {
    int q;
    fin >> q;

    while (q--) {
        int p, x;
        fin >> p;
        if (p == 1) {
            fin >> x;

            vsize++; hsize++;

            val[vsize] = x;
            heap[hsize] = vsize;
            pos[vsize] = hsize;

            push(hsize);
        }

        else if (p == 2) {
            fin >> x;

            val[x] = -1;
            push(pos[x]);

            pos[heap[1]] = 0;
            heap[1] = heap[hsize--];
            pos[heap[1]] = 1;

            pop(1);
        }

        else fout << val[heap[1]] << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}