Cod sursa(job #1563508)

Utilizator florin.elfusFlorin Elfus florin.elfus Data 6 ianuarie 2016 05:08:04
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
//ericut scrie cod urat

#include <bits/stdc++.h>

using namespace std;

const int kNMax = 200200;

int nodes;
int get_node[kNMax];

struct heap_node {
    int val;
    int when;
} h[kNMax];

heap_node make(int _val, int _when) {
    heap_node foo;
    foo.val = _val;
    foo.when = _when;
    return foo;
}

void swap_nodes(int nod1, int nod2) {
    swap(h[nod1].val, h[nod2].val);
    swap(h[nod1].when, h[nod2].when);
    get_node[h[nod1].when] = nod1;
    get_node[h[nod2].when] = nod2;
}

void climb(int nod) {
    while (nod > 1 && h[nod / 2].val > h[nod].val) {
        swap_nodes(nod, nod / 2);
        nod = nod / 2;
    }
}

void fall(int nod) {
    int son;
    do {
        son = 0;
        if (2 * nod <= nodes && h[2 * nod].val < h[nod].val)
            son = 2 * nod;
        if (2 * nod + 1 <= nodes && h[2 * nod + 1].val < h[nod].val && h[2 * nod + 1].val < h[2 * nod].val)
            son = 2 * nod + 1;
        if (son) {
            swap_nodes(nod, son);
            nod = son;
        }
    } while (son);
}

int main() {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    int n;
    int tot_added = 0;

    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
        int op;
        scanf("%d", &op);
        if (op == 1) {
            int x;
            scanf("%d", &x);
            h[++nodes] = make(x, ++tot_added);
            get_node[tot_added] = nodes;
            climb(nodes);
        }
        if (op == 2) {
            int x;
            scanf("%d", &x);
            x = get_node[x];
            h[x].val = h[nodes].val;
            h[x].when = h[nodes].when;
            --nodes;
            if (x > 1 && h[x].val < h[x / 2].val)
                climb(x);
            else
                fall(x);
        }
        if (op == 3)
            printf("%d\n", h[1].val);
    }

    return 0;
}