Cod sursa(job #2464384)

Utilizator Radu_FilipescuFilipescu Radu Radu_Filipescu Data 28 septembrie 2019 14:41:42
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <fstream>

using namespace std;

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

const int NMAX = 200002;

int N;
int heap[NMAX], heap2[NMAX], h_size;
int pos[NMAX], nr_in;

void BubbleUp( int nod )
{
    if( nod == 1 ) return;

    if( heap[nod] < heap[nod / 2] )
    {
        pos[ heap2[nod] ] = nod / 2;
        pos[ heap2[nod / 2] ] = nod;
        swap( heap[nod], heap[nod / 2] );
        swap( heap2[nod], heap2[nod / 2] );

        BubbleUp( nod / 2 );
    }
}

void BubbleDown( int nod )
{
    if( nod * 2 > h_size ) return;

    int v1, v2;

    v1 = heap[nod * 2];

    if( nod * 2 + 1 > h_size ) v2 = 2000000000;

    if( heap[nod] < min( v1, v2 ) ) return;

    if( v1 < v2 )
    {
       pos[ heap2[nod] ] = nod * 2;
       pos[ heap2[nod * 2] ] = nod;

       swap( heap[nod], heap[nod * 2] );
       swap( heap2[nod], heap2[nod * 2] );

       BubbleDown( nod * 2 );
    }
    else
    {
       pos[ heap2[nod] ] = nod * 2 + 1;
       pos[ heap2[nod * 2 + 1] ] = nod;

       swap( heap[nod], heap[nod * 2 + 1] );
       swap( heap2[nod], heap2[nod * 2 + 1] );

       BubbleDown( nod * 2 + 1 );
    }
}

void HeapAdd( int val )
{
    heap[++h_size] = val;
    pos[++nr_in] = h_size;
    heap2[h_size] = nr_in;

    BubbleUp( h_size );
}

void HeapDel( int nod )
{
    pos[ heap2[h_size] ] = nod;
    heap2[nod] = heap2[h_size];

    swap( heap[nod], heap[h_size] );
    --h_size;

    BubbleDown( nod );
}

void Read()
{
    fin >> N;

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

       fin >> t;
       if( t == 1 || t == 2 ) fin >> x;

       if( t == 1 ) HeapAdd( x );
       if( t == 2 ) HeapDel( pos[x] );
       if( t == 3 ) fout << heap[1] << '\n';

       /*for( int i = 1; i <= h_size; ++i )
         fout << heap[i] << ' ';

       fout << '\n';

       for( int i = 1; i <= h_size; ++i )
         fout << heap2[i] << ' ';

       fout << '\n';

       for( int i = 1; i <= nr_in; ++i )
         fout << pos[i] << ' ';

       fout << "\n\n"; */
    }
}

int main()
{
    Read();

    return 0;
}