Cod sursa(job #1259331)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 9 noiembrie 2014 22:25:30
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include<fstream>

using namespace std;

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

const int nmax = 200000;
const int inf = 1 << 30;
int w, hw, v[ nmax + 10 ], p[ nmax + 10 ], h[ 2 * nmax ];

void schimb( int x, int y ) {
    p[ h[ x ] ] = y;
    p[ h[ y ] ] = x;

    int aux = h[ x ];
    h[ x ] = h[ y ];
    h[ y ] = aux;
}
void urcare( int poz ) {
    while ( 1 < poz && v[ h[ poz / 2 ] ] > v[ h[ poz ] ] ) {
        schimb( poz, poz / 2 );
        poz /= 2;
    }
}
void coborare( int poz ) {
    while ( 2 * poz <= hw ) {
        if ( 2 * poz + 1 >= hw || v[ h[ 2 * poz ] ] < v[ h[ 2 * poz + 1 ] ] ) {
            schimb( poz, 2 * poz );
            poz = 2 * poz;
        } else {
            schimb( poz, 2 * poz + 1 );
            poz = 2 * poz + 1;
        }
    }
}
void insert_elem() {
    h[ hw ++ ] = w;
    p[ w ] = hw - 1;
    urcare( p[ w ] );
}
void erase_elem( int x ) {
    int poz = p[ x ];
    h[ poz ] = h[ hw - 1 ];
    -- hw;
    if ( h[ poz / 2 ] > h[ poz ] ) {
        urcare( poz );
    } else {
        coborare( poz );
    }
}
int main() {
    int n, t, x;
    fin >> n;
    w = hw = 1;
    for( int i = 0; i < n; ++ i ) {
        fin >> t;
        if ( t == 1 ) {
            fin >> v[ w ];
            insert_elem();
            ++ w;
        } else if ( t == 2 ) {
            fin >> x;
            erase_elem( x );
        } else {
            fout << v[ h[ 1 ] ] << "\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}