Pagini recente » Cod sursa (job #2823335) | Cod sursa (job #2642951) | Cod sursa (job #87049) | Cod sursa (job #2132469) | Cod sursa (job #1514270)
#include <cstdio>
using namespace std;
FILE *f = fopen ( "heapuri.in" , "r" ) , *g = fopen ( "heapuri.out" , "w" );
const int MAX = 200005;
int nrReq , type , father , aux , value , Size , heap [ MAX ] , indexed [ MAX ] , i , pos , indexed_1 [ MAX ] , left , right;
void heapify ( int index , int i )
{
father = index / 2;
while ( heap [ index ] < heap [ father ] && father )
{
aux = heap [ index ] , heap [ index ] = heap [ father ] , heap [ father ] = aux;
indexed [ indexed_1 [ father ] ] = index;
index /= 2 , father = index / 2;
}
indexed [ i ] = index;
indexed_1 [ index ] = i;
}
void shiftdown ( int index , int i )
{
//find the minimum
left = index * 2 , right = left + 1;
if ( left < Size && heap [ left ] < heap [ index ] && heap [ left ] < heap [ right ] )
{
aux = heap [ left ] , heap [ left ] = heap [ index ] , heap [ index ] = aux;
indexed [ indexed_1 [ left ] ] = index;
indexed [ i ] = left;
shiftdown ( left , i );
}
else
if ( right < Size && heap [ right ] < heap [ index ] && heap [ right ] < heap [ left ] )
{
aux = heap [ right ] , heap [ right ] = heap [ index ] , heap [ index ] = aux;
indexed [ indexed_1 [ right ] ] = index;
indexed [ i ] = right;
shiftdown ( right , i );
}
}
void add()
{
//get node value
fscanf ( f , "%d" , &value );
//insert it into the heap along with its index
heap [ ++Size ] = value;
heapify ( Size , Size );
}
void remove()
{
fscanf ( f , "%d" , &pos );
//delete pos-th element
heap [ indexed [ pos ] ] = heap [ Size ] , Size --;
shiftdown ( indexed [ pos ] , pos );
}
void printMin()
{
fprintf ( g , "%d\n" , heap [ 1 ] );
}
void read()
{
fscanf ( f , "%d" , &nrReq );
for ( i = 1 ; i <= nrReq ; i ++ )
{
//get the type of request
fscanf ( f , "%d" , &type );
if ( type == 1 )
add();
else
if ( type == 2 )
remove();
else
printMin();
}
}
int main()
{
read();
return 0;
}