Cod sursa(job #989894)

Utilizator manutrutaEmanuel Truta manutruta Data 26 august 2013 20:16:44
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
# include <iostream>
# include <fstream>
using namespace std;

# define MAXN 200010

# define father(x) (x >> 1)
# define leftSon(x) (x << 1)
# define rightSon(x) ((x << 1) + 1)

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

int n = 0, l = 0;
int vec[MAXN];
int heap[MAXN];
int pos[MAXN];

void insert(int x) {
    while (father(x) != 0 && vec[heap[x]] < vec[heap[father(x)]]) {
        swap(heap[x], heap[father(x)]);
        pos[heap[x]] = x;
        pos[heap[father(x)]] = father(x);
        x = father(x);
    }
}

void remove(int x) {
    int y = 0;
    while (x != y) {
        y = x;
        if (leftSon(y) <= l && vec[heap[x]] > vec[heap[leftSon(y)]]) {
            x = leftSon(y);
        }
        if (rightSon(y) <= l && vec[heap[x]] > vec[heap[rightSon(y)]]) {
            x = rightSon(y);
        }
        swap(heap[x], heap[y]);
        pos[heap[x]] = x;
        pos[heap[y]] = y;
    }
}

int main()
{
    int q;
    f >> q;
    for (int i = 1; i <= q; i++) {
        int op, x;
        f >> op;

        switch (op) {
            case 1:
                f >> x;

                l++;
                n++;
                vec[n] = x;
                heap[l] = n;
                pos[n] = l;
                insert(l);

                /*for (int i = 1; i <= n; i++) {
                    cout << vec[i] << ' ';
                }
                cout << endl;*/

                break;
            case 2:
                f >> x;

                vec[x] = -1;
                insert(pos[x]);

                pos[heap[1]] = 0;
                heap[1] = heap[l--];
                pos[heap[1]] = -1;
                remove(x);

                break;
            case 3:
                g << vec[heap[1]] << endl;
                break;
        }
    }

    /*cout << father(4) << endl;
    cout << leftSon(4) << endl;
    cout << rightSon(4) << endl;*/

    return 0;
}