Cod sursa(job #979011)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 31 iulie 2013 09:09:03
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>

using namespace std;

#define Nmax 200004

#define Parent(i) i/2
#define LeftSon(i) 2*i
#define RightSon(i) 2*i+1

int H[Nmax]; // h
int poz[Nmax]; //poz
int order[Nmax]; //ind

int N, M, ord;

void swapp( int a, int b )
{
    swap( order[a], order[b] );
    poz[ order[a] ] = a;
    poz[ order[b] ] = b;
    swap( H[a], H[b] );
}

void DownHeap( int poz1 )
{
    int k = poz1;
    int j;

    do
    {
        j = k;

        if ( LeftSon(j) <= N && H[LeftSon(j)] < H[k] )   k = LeftSon(j);
        if ( RightSon(j) <= N && H[RightSon(j)] < H[k] ) k = RightSon(j);


        swapp( j, k );

    } while( j != k );

}

void UpHeap( int poz1 )
{
    int k = poz1;
    int j;
    do
    {
        j = k;

        if ( j > 1 && H[Parent(j)] > H[k] )  k = Parent(j);

        swapp( j, k );

    } while( j != k );
}

void InsertHeap( int key )
{
    H[ ++N ] = key;
    poz[ ++ord ] = N;
    order[N] = ord;

    UpHeap( N );
}

void DeleteHeap( int key )
{
    int pz = poz[key];

    swap( order[pz], order[N] );
    poz[ order[pz] ] = pz;
    poz[ order[N] ] = N;
    swap( H[pz], H[N] );

    N--;

    UpHeap( pz );
    DownHeap( pz );
}

int main()
{
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");

    f >> M;

    for ( int tip, key, i = 1; i <= M; i++ )
    {
        f >> tip;

        switch( tip )
        {
            case 1:
                    f >> key;
                    InsertHeap(key);
                    break;

            case 2:
                    f >> key;
                    DeleteHeap(key);
                    break;

            case 3:
                    g << H[1] << "\n";
                    break;

            default: break;
        }
    }

    return 0;
}