Cod sursa(job #2364530)

Utilizator nurof3nCioc Alex-Andrei nurof3n Data 4 martie 2019 09:31:47
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <fstream>

using namespace std;

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

const int MAXM = 200001;
int H[MAXM]; //retinem indicii pe care se afla elementele in V
int V[MAXM], poz[MAXM];
int M, N, nr;

inline int left (int nod) {
    return 2 * nod;
}
inline int right (int nod) {
    return 2 * nod + 1;
}
inline int tata (int nod) {
    return nod / 2;
}
///MIN-HEAP
inline int min () {
    return V[H[1]];
}

void sift (int K) { ///"cerne" nodul K (in jos), astfel incat sa se restabileasca structura de min-heap
    if (left (K) > N && right (K) > N) ///este nod terminal
        return;
    if(V[H[K]] <= V[H[left(K)]] && (right(K) > N || V[H[K]] <= V[H[right(K)]])) ///am ajuns la structura de min-heap
        return;
    if(right(K) > N) {
        swap (H[K], H[left (K)]);
        poz[H[K]] = K;
        poz[H[left(K)]] = left(K);
        sift (left (K));
    } else if(V[H[left(K)]] > V[H[right(K)]]) {
        swap (H[K], H[right (K)]);
        poz[H[K]] = K;
        poz[H[right(K)]] = right(K);
        sift (right (K));
    } else {
        swap (H[K], H[left (K)]);
        poz[H[K]] = K;
        poz[H[left(K)]] = left(K);
        sift (left (K));
    }
}

void percolate (int K) { ///"infiltreaza" nodul K (in sus), astfel incat sa se restabileasca structura de min-heap
    if (K == 1)
        return;
    if (V[H[K]] < V[H[tata (K)]]) {
        swap (H[K], H[tata (K)]);
        poz[H[K]] = K;
        poz[H[tata(K)]] = tata(K);
        percolate (tata (K) );
    }
}

void erase(int k) { //O(logN)
    V[k] = -1;
    int K = poz[k];
    poz[k] = -1;
    if(K == N) {
        --N;
        return;
    }
    H[K] = H[N--];
    poz[H[K]] = K;
    if(tata(K) && V[H[K]] < V[H[tata(K)]])
        percolate(K);
    else
        sift(K);
}

void insert(int x) { //O(logN)
    V[++nr] = x;
    H[++N] = nr;
    poz[nr] = N;
    percolate(N);
}

int main() {
    in >> M;
    int op, x, k;
    for(int i = 1; i <= M; i++) {
        in >> op;
        if(op == 1) {
            in >> x;
            insert(x);
        } else if(op == 2) {
            in >> k;
            erase(k); //stergem elementul care a intrat al k-lea in heap
        } else
            out << min() << '\n';
    }

    return 0;
}