Cod sursa(job #978986)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 30 iulie 2013 23:03:27
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 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
#define Min(H) H[1]

int position[Nmax];
int order[Nmax];

void InitHeap( int *H )
{
    for ( int i = 0; i < Nmax; ++i )
            H[i] = 0;
}

void DownHeap( int *H, int N, int poz )
{
    int k = poz;
    int j;

    do
    {
        j = k;

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

        swap( H[j], H[k] );

        swap( position[ order[j] ], position[ order[k] ] );

    } while( j != k );
}

void UpHeap( int *H, int N, int poz )
{
    int k = poz;
    int j;

    do
    {
        j = k;

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

        swap( H[j], H[k] );

        swap( position[ order[j] ], position[ order[k] ] );

    } while( j != k );
}

void InsertHeap( int *H, int &N, int key, int poz )
{
    H[ ++N ] = key;

    order[N] = poz; /// pozitie in sir initial
    position[ order[N] ] = poz; /// positie in Heap

    UpHeap( H, N, N );
}

void DeletePoz( int *H, int &N, int poz )
{
    H[poz] = H[N];

    DownHeap( H, N, poz );

    N--;
}

int main()
{
    int H[Nmax], M, N = 0;
    int K = 0;

    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( H, N, key, ++K );
                    break;

            case 2:
                    f >> key;
                    DeletePoz(H, N, order[key]);
                    break;

            case 3:
                    g << Min(H) << "\n";
                    break;

            default: break;
        }
    }

    return 0;
}