Cod sursa(job #1197910)

Utilizator SpiderManSimoiu Robert SpiderMan Data 14 iunie 2014 01:51:12
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include <fstream>
#include <vector>
using namespace std;

const int MAX_HEAP_SIZE = 200010;
typedef int Heap[MAX_HEAP_SIZE];

Heap H;
int T, N, type, x;
int V[MAX_HEAP_SIZE], pos[MAX_HEAP_SIZE];

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

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

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

inline int min(Heap H) {
    return H[1];
}

void sift(Heap H, int N, int K) {
    int son;
    do {
        son = 0;
        // Alege un fiu mai mare ca tatal.
        if (left_son(K) <= N) {
            son = left_son(K);
            if (right_son(K) <= N && V[H[right_son(K)]] < V[H[left_son(K)]]) {
                son = right_son(K);
            }
            if (V[H[son]] > V[H[K]]) {
                son = 0;
            }
        }

        if (son) {
            swap(H[K], H[son]);  // Functie STL ce interschimba H[K] cu H[son]
            swap(pos[H[K]], pos[H[son]]);
            K = son;
        }
    } while (son);
}

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

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

    H[K] = key;
    pos[key] = K;
}

void insert(Heap H, int& N, int key) {
    H[++N] = key;
    pos[key] = N;
    percolate(H, N, N);
}

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

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

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

    for (f >> T; T; --T) {
        f >> type;
        if (type == 1) {
            f >> V[++V[0]];
            insert(H, N, V[0]);
        } else if (type == 2) {
            f >> x;
            cut(H, N, pos[x]);
        } else {
            g << V[min(H)] << "\n";
        }
    }
}