Cod sursa(job #942795)

Utilizator Mihai22eMihai Ionut Enache Mihai22e Data 23 aprilie 2013 16:52:25
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>
using namespace std;

const int MAX_HEAP_SIZE = 200002;

typedef int Heap[MAX_HEAP_SIZE];

int Q, x, t, N;
int pos[MAX_HEAP_SIZE], val[MAX_HEAP_SIZE];
Heap H;

inline int father(int nod){
    return nod/2;
}

inline int left_son(int nod){
    return 2*nod;
}

inline int right_son(int nod){
    return 2*nod+1;
}

inline void percolate(Heap H, int N, int K){
    int tmp = H[K];

    while(K > 1 && val[tmp] < val[H[father(K)]]){
        H[K] = H[father(K)];
        pos[H[K]] = K;
        K = father(K);
    }
    H[K] = tmp;
    pos[H[K]] = K;
}

inline void sift(Heap H, int N, int K){
    int son = 0;

    do{
        son = 0;
        if(left_son(K) <= N)
            son = left_son(K);
        if(right_son(K) <= N && val[H[right_son(K)]] < val[H[left_son(K)]])
            son = right_son(K);

        if(val[H[son]] >= val[H[K]])
            son = 0;
        if(son){
            int tmp = H[K];

            H[K] = H[son], H[son] = tmp;
            pos[H[K]] = K, pos[H[son]] = son;
        }
    }while(son);
}

inline void cut(Heap H, int &N, int K){
    H[K] = H[N];
    --N;
    pos[H[K]] = K;

    if(K > 1 && val[H[K]] < val[H[father(K)]])
        percolate(H, N, K);
    else sift(H, N, K);
}

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

    f >> Q;
    for(int q = 1, nr = 0; q <= Q; ++q){
        f >> t;
        if(t == 1){
            f >> x;
            ++N, ++nr;
            H[N] = nr, pos[nr] = N, val[nr] = x;
            if(N > 1 && val[ H[N] ] < val[ H[father(N)] ])
                percolate(H, N, N);
        }
        else if(t == 2){
            f >> x;
            cut(H, N, pos[x]);
        }
        else g << val[H[1]] << '\n';
    }

    f.close();
    g.close();

    return 0;
}