Cod sursa(job #1514309)

Utilizator jimcarterJim Carter jimcarter Data 30 octombrie 2015 23:16:52
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <cstdio>
using namespace std;

FILE *f = fopen ( "heapuri.in" , "r" ) , *g = fopen ( "heapuri.out" , "w" );

const int MAX = 200005;
int nrReq , type , father , aux , value [ MAX ] , Size , heap [ MAX ] , indexed [ MAX ] , i , pos , indexed_1 [ MAX ] , left , right , nr , son;

void heapify ( int index )
{
    father = index / 2;
    while ( value [ heap [ index ] ] < value [ heap [ father ] ] && father )
    {
        aux = heap [ index ] , heap [ index ] = heap [ father ] , heap [ father ] = aux;
        indexed [ heap [ index ] ] = index;
        indexed [ heap [ father ] ] = father;
        index /= 2 , father = index / 2;
    }
}

void shiftdown ( int index )
{
    //find the minimum
    son = -1;
    while ( index != son )
    {
        left = index * 2 , right = left + 1;
        son = index;
        if ( left <= Size && value [ heap [ left ] ] < value [ heap [ index ] ] )
            index = left;
        if ( right <= Size && value [ heap [ right ] ] < value [ heap [ index ] ] )
            index = right;

        aux = heap [ index ] , heap [ index ] = heap [ son ] , heap [ son ] = aux;
        indexed [ heap [ index ] ] = index;
        indexed [ heap [ son ] ] = son;
    }
}

void add()
{
    //get node value
    fscanf ( f , "%d" , &value [ ++nr ] );
    //insert it into the heap along with its index
    heap [ ++Size ] = nr;
    indexed [ nr ] = Size;
    heapify ( Size );
}

void remove()
{
    fscanf ( f , "%d" , &pos );
    //delete pos-th element
    value [ pos ] = -1;
    heapify ( indexed [ pos ] );
    indexed [ heap [ 1 ] ] = 0;
    heap [ 1 ] = heap [ Size ] , Size --;
    indexed [ heap [ 1 ] ] = 1;
    shiftdown ( 1 );
}

void printMin()
{
    fprintf ( g , "%d\n" , value [ heap [ 1 ] ] );
}

void read()
{
    fscanf ( f , "%d" , &nrReq );

    for ( i = 1 ; i <= nrReq ; i ++ )
    {
        //get the type of request
        fscanf ( f , "%d" , &type );
        if ( type == 1 )
            add();
        else
            if ( type == 2 )
                remove();
            else
                printMin();
    }
}

int main()
{
    read();
    return 0;
}