Cod sursa(job #1486433)

Utilizator Corneliu10Dumitru Corneliu Corneliu10 Data 14 septembrie 2015 20:54:17
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int N , poz [200001] , heap [200001]  , v [200001] , lg_heap , lg_v  ;
// poz  =  pozitia fiecarui elem  in HEAP  , v = numerele citite in ordine


void swap ( int p , int q )
{
    int aux = heap [p] ;
    heap [p] = heap [q] ;
    heap [q] = aux ;
    poz [ heap [p] ] = p ;
    poz [ heap [q] ] = q ;
}

void urca ( int p )      //percolate
{
    while ( p > 1 && v [ heap [p] ] < v [ heap [p/2 ] ] )
    {
        swap ( p , p / 2 ) ; // schimb fiu cu tata
        p /= 2 ;
    }
}

void InsertHeap ( int x )
{
    heap [ ++ lg_heap ] = x ;
    poz [ x ] = lg_heap ;
    urca ( lg_heap );
}

void coboara ( int p )  // echivalent cu SIFT
{
    int fiust = 2*p , fiudr = 2 * p + 1 , bun = p ;

    if ( fiust <= lg_heap && v [ heap [ fiust ] ] < v [ heap [ bun ] ] )
        bun = fiust ;
                                                               // determin fiul "minim"
    if ( fiudr <= lg_heap && v [ heap [ fiudr ] ] < v [ heap [ bun ] ] )
        bun = fiudr ;

    if ( bun != p )
    {
        swap ( p , bun ) ;
        coboara ( bun );
    }
}

void DeleteHeap(int p)
{
    swap ( p , lg_heap -- );
    urca ( p ) ;
    coboara ( p ) ;
}

int Minim ()
{
    return v [ heap [1] ] ;
}

int main()
{
    fin >> N ;
    int a , b ;
    while ( N >= 1 )
    {
        fin >> a ;
        switch ( a )
        {
            case 1 : fin >> b ; v [ ++ lg_v ] = b ; InsertHeap ( lg_v ) ; break ;
            case 2 : fin >> b ; DeleteHeap ( poz[b] ) ; break ;
            case 3 : fout << Minim () << "\n" ; break ;
        }
        -- N ;
    }

    return 0;
}