Cod sursa(job #1205477)

Utilizator pop_bogdanBogdan Pop pop_bogdan Data 6 iulie 2014 20:02:09
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <vector>
using namespace std;

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

vector<pair<int,int> > H; int  N, 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)].first < H[LeftSon(K)].first) )
                Son = RightSon(K);
           if ( H[K].first <= H[Son].first )
            Son = 0;
       }
       if ( Son )
       {
           swap(H[K],H[Son]);
           swap(Pos2[H[K].second],Pos2[H[Son].second]);
           K = Son;
       }

    } while ( Son );
}

void Percolate(int K)
{
    while ( Father(K) > 0 && H[Father(K)].first > H[K].first )
    {
        swap(H[Father(K)],H[K]);
        swap(Pos2[H[K].second],Pos2[H[Father(K)].second]);
        K = Father(K);
    }
}

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

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

int main()
{
    H.resize(200001);
    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[y]);
        }
        if ( x == 3 )
            os << H[1].first << '\n';
    }

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