Cod sursa(job #2217903)

Utilizator nurof3nCioc Alex-Andrei nurof3n Data 2 iulie 2018 15:54:23
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.14 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(V[H[K]] > V[H[left(K)]] && (right(K) > N || V[H[left(K)]] <= V[H[right(K)]]))
    {
        swap (poz[H[K]], poz[H[left(K)]]);
        swap (H[K], H[left (K)]);
        sift (left (K) );
    }
    else
    {
        swap (poz[H[K]], poz[H[right(K)]]);
        swap (H[K], H[right (K)]);
        sift (right (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 (poz[H[K]], poz[H[tata(K)]]);
        swap (H[K], H[tata (K)]);
        percolate (tata (K) );
    }
}
void erase(int k)//O(logN)
{
    V[k] = -1;
    int K = poz[k];
    poz[k] = -1;
    poz[H[N]] = K;
    H[K] = H[N--];
    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 ind-lea in heap
        }
        else
            out << min() << '\n';
    }

    return 0;
}