Cod sursa(job #1052676)

Utilizator Teodor94Teodor Plop Teodor94 Data 11 decembrie 2013 17:44:25
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

#define MAX_N 200000

vector< int > heap;
int n, pos_heap[MAX_N + 1], pos_cron[MAX_N + 1];

void up_heap( int pos ) {
	if ( pos > 1 && heap[pos >> 1] > heap[pos] ) {
		swap( heap[pos >> 1], heap[pos] );
		swap( pos_heap[pos_cron[pos >> 1]], pos_heap[pos_cron[pos]] );
		swap( pos_cron[pos >> 1], pos_cron[pos] );
		
		up_heap( pos >> 1 );
	}
}

void down_heap( int pos ) {
	if ( ( pos << 1 ) >= heap.size() )
		return;
		
	int next = ( pos << 1 );
	if ( next + 1 < heap.size() && heap[next + 1] < heap[next] )
		++next;
		
	if ( heap[next] < heap[pos] ) {
		swap( heap[next], heap[pos] );
		swap( pos_heap[pos_cron[pos]], pos_heap[pos_cron[next]] );
		swap( pos_cron[pos], pos_cron[next] );
		
		down_heap( next );
	}
}

void insert( int x ) {
	heap.push_back( x );
	
	++n;
	pos_heap[n] = heap.size() - 1;
	pos_cron[heap.size() - 1] = n;
	
	up_heap( heap.size() - 1 );
}

void erase( int pos ) {
	heap[pos] = heap[heap.size() - 1];
	heap.pop_back();
	
	down_heap( pos );
	up_heap( pos );
}

int main() {
	FILE *fin, *fout;
	
	int t;
	fin = fopen( "heapuri.in", "r" );
	fout = fopen( "heapuri.out", "w" );
	
	heap.push_back( 0 );
	
	fscanf( fin, "%d", &t );
	while ( t ) {
		int type, x;
		fscanf( fin, "%d", &type );
		
		if ( type == 1 ) {
			fscanf( fin, "%d", &x );
			insert( x );
		} else if ( type == 2 ) {
			fscanf( fin, "%d", &x );
			erase( pos_heap[x] );
		} else
			fprintf( fout, "%d\n", heap[1] );
		
		--t;
	}
	
	fclose( fin );
	fclose( fout );
}