Cod sursa(job #1486605)

Utilizator DorelBarbuBarbu Dorel DorelBarbu Data 15 septembrie 2015 11:03:55
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.16 kb
#include <iostream>
#include <cstdio>
using namespace std;

const int MAXN = 200000;

int heap[4*MAXN+1], where[MAXN+1], nodesInHeap, N, index, who[4*MAXN+1];

int leftSon(int poz)
{
    return 2*poz;
}

int rightSon(int poz)
{
    return 2*poz + 1;
}

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

bool exists(int son)
{
    return son <= nodesInHeap;
}

void change(int x, int y)
{
    swap( heap[ x ], heap[ y ] );
    swap( who[ x ], who[ y ] );
    swap( where[ who[ x ] ], where[ who[ y ] ] );
}

void upInHeap(int poz)
{
    while( poz != 1 && heap[ father( poz ) ] > heap[ poz ] )
    {
        change(poz, father(poz));
        poz = father( poz );
    }
}

void downInHeap(int poz)
{
    while( 1 )
    {
        int right = rightSon( poz ), left = leftSon( poz ), son = -1;

        if( exists( left ) == true && exists( right ) == true )
        {
            if( heap[ right ] < heap[ left ] )
                son = right;
            else
                son = left;
        }
        else
        {
            if( exists( left ) == false )
                return;
            else son = left;
        }

        if( son == -1 )
            return;

        if( heap[ poz ] > heap[ son ] )
            change( poz, son );
        else return;

        poz = son;
    }
}

void removeFromHeap(int poz)
{
    change(poz,nodesInHeap);
    nodesInHeap--;
    upInHeap( poz );
    downInHeap( poz );
}

void insertInHeap(int value, int index)
{
    heap[ ++nodesInHeap ] = value;
    where[ index ] = nodesInHeap;
    who[ nodesInHeap ] = index;
    upInHeap( nodesInHeap );
}


int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);

    scanf("%d",&N);

    for(int i = 1; i <= N; i++)
    {
        int cod, x, y;

        scanf("%d",&cod);

        if( cod == 1 )
        {
            scanf("%d",&x);
            insertInHeap( x, ++index );
        }
        else
        if( cod == 2 )
        {
            scanf("%d",&x);
            removeFromHeap(where[ x ]);
        }
        else printf("%d\n",heap[ 1 ]);
    }

    return 0;
}