Cod sursa(job #1205471)

Utilizator pop_bogdanBogdan Pop pop_bogdan Data 6 iulie 2014 19:30:48
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
using namespace std;

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

int H[200001], N, Pos[200001], Pos2[200001], V;

inline int Father(int K)
{
    return K/2;
}

inline int RightSon(int K)
{
    return 2*K+1;
}

inline int LeftSon(int K)
{
    return 2*K;
}

void Sift(int K)
{
    int Son;
    do
    {
       Son = 0;
       if ( LeftSon(K) <= N )
       {
           Son = LeftSon(K);
           if ( RightSon(K) <= N && H[RightSon(K)] < H[LeftSon(K)] )
                Son = RightSon(K);
           if ( H[K] <= H[Son] )
            Son = 0;
       }
       if ( Son )
       {
           swap(H[K],H[Son]);
           swap(Pos2[H[K]],Pos2[H[Son]]);
           K = Son;
       }

    } while ( Son );
}

void Percolate(int K)
{
    int key = H[K];
    while ( K > 1 && key < H[Father(K)] )
    {
        swap(H[Father(K)],H[K]);
        swap(Pos2[H[K]],Pos2[H[Father(K)]]);
        K = Father(K);
    }
    H[K] = key;
}

void Insert(int key)
{
    ++V;
    Pos[V] = key;
    H[++N] = key;
    Pos2[key] = N;
    Percolate(N);
}

void Delete( int K)
{
    H[K] = H[N];
    Pos2[H[N]] = K;
    Pos2[H[K]] = 0;
    --N;
    if ( (K > 1) && (H[K] < H[Father(K)]) )
        Percolate(K);
    else
        Sift(K);
}

int main()
{
    int Q, x, y;
    is >> Q;
    for ( int i = 1; i <= Q; ++i )
    {
        is >> x;
        if ( x == 1 )
        {
            is >> y;
            Insert(y);
        }
        if ( x == 2 )
        {
            is >> y;
            Delete(Pos2[Pos[y]]);
        }
        if ( x == 3 )
            os << H[1] << '\n';
    }

    is.close();
    os.close();
}