Cod sursa(job #1471123)

Utilizator DysKodeTurturica Razvan DysKode Data 13 august 2015 09:42:32
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <fstream>
#include <map>

using namespace std;

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

int Heap[200010],poz[200010],i,j,N,m,op,val,t;
map <int,int> vec;

int father( int X )
{
    return X / 2;
}

int left_son( int X )
{
    return X * 2;
}

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

void percolate( int Heap[] , int N , int K )
{
    while( K > 1 && Heap[ father( K ) ] > Heap[ K ] )
    {
        swap( Heap[ father( K ) ] , Heap[ K ] );
        swap( poz[ vec[ Heap[ father( K ) ] ] ] , poz[ vec[ Heap[ K ] ] ] );
        K = father( K );
    }
}

void sift( int Heap[] , int N , int K )
{
    int son;

    do
    {
        son = 0;
        if( left_son( K ) <= N )
        {
            son = left_son( K );

            if( right_son( K ) <= K && Heap[ left_son( K ) ] > Heap[ right_son( K ) ] )
            {
                son = right_son( K );
            }

            if( Heap[ son ] > Heap[ K ] )
                son = 0;
        }

        if( son )
        {
            swap( Heap[ son ] , Heap[ K ] );
            swap( poz[ vec[ Heap[ son ] ] ] , poz[ vec[ Heap[ K ] ] ] );
            K = son;
        }

    }while( son );
}

void add( int Heap[] , int& N , int val )
{
    N++;
    Heap[ N ] = val;
    percolate( Heap , N , N );
}

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

    if( Heap[ K ] < Heap[ father( K ) ] )
    {
        percolate( Heap , N , K );
    }
    else
    {
        sift( Heap , N , K );
    }
}

int main()
{

    fin>>m;
    for( i = 1 ; i <= m ; i++ )
    {
        fin>>op;
        if( op == 3 )
        {
            fout<<Heap[ 1 ]<<'\n';
        }
        else if( op == 1 )
        {
            fin>>val;
            ++t;
            poz[ t ] = N + 1;
            vec[ val ] = N + 1;
            add( Heap , N , val );
        }
        else if( op == 2 )
        {
            fin>>val;
            cut( Heap , N , poz[ val ] );
        }
    }

return 0;
}