Cod sursa(job #1075906)

Utilizator danny794Dan Danaila danny794 Data 9 ianuarie 2014 18:30:06
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <cstdio>

using namespace std;

const int NMAX = 200005;
int N, H, A;
int heap[NMAX], position[NMAX], array[NMAX];

inline void swap(int a, int b) {
    int change = heap[a];
    heap[a] = heap[b];
    heap[b] = change;

    position[heap[a]] = a;
    position[heap[b]] = b;
}

inline void up_heapify(int index) {
    while( index > 1 &&  array[heap[index]] < array[heap[index >> 1]] ) {
        swap(index, index >> 1);
        index >>= 1;
    }
}

inline void insert(int elem) {
    array[++A] = elem;
    heap[++H] = A;
    position[A]= H;
    up_heapify(H);
}

void down_heapify(int x) {
    int aux, y = 0;

    while (x != y)
    {
        y = x;

        if (y*2<=H && array[heap[x]]>array[heap[y*2]]) x = y*2;
        if (y*2+1<=H && array[heap[x]]>array[heap[y*2+1]]) x = y*2+1;

        aux = heap[x];
        heap[x] = heap[y];
        heap[y] = aux;

        position[heap[x]] = x;
        position[heap[y]] = y;
    }}

inline void remove(int index) {
    swap(index, H);
    position[heap[H]] = -1;
    H--;
    down_heapify(index);
}

void read() {
    freopen( "heapuri.in", "r", stdin );
    freopen( "heapuri.out", "w", stdout );
    scanf("%i", &N);
    int type, n;
    for(int i = 0; i < N; i++) {
        scanf("%i", &type);
        switch(type) {
            case(1): scanf("%i", &n); insert(n); break;
            case(2): scanf("%i", &n); remove(position[n]); break;
            case(3): printf("%i\n", array[heap[1]]); break;
        }
    }
}

int main() {
    read();
    return 0;
}