Cod sursa(job #496292)

Utilizator cnt_tstcont teste cnt_tst Data 28 octombrie 2010 12:32:15
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include<stdio.h>
#include<algorithm>
using namespace std;

FILE*f=fopen("heapuri.in","r");
FILE*g=fopen("heapuri.out","w");

int i,NN,heap[200100],n,caz,c,p,x,poz[200100],ordine,u,m;

void add_heap(int x){
	
	heap[++n] = x;
	poz[n] = n;
	c = n; p = n/2;
	while( p != 0 && heap[p] > heap[c] ){
		swap(heap[p],heap[c]);
		swap(poz[p],poz[c]);
		c = p; 
		p = p / 2;
	}
	
}
void remove_heap(int x){
	
	p = 1 ; u = n;
	while ( p <= u ){
		
		m = p +(u - p )/2;
		if ( heap[m] == poz[x])
			break;
		if(heap[m] > poz[x] )
			u = m - 1;
		else
			p = m + 1;
		
	}
	
	swap(heap[m],heap[n--]);
	poz[m] = n+1;
	
	p = m ; c = 2 * p;
	if ( c > n ) c = n;
	while ( c <= n ){
		if ( c + 1 <= n && heap[c+1] < heap[c] )
			++c;
		
		if ( heap[p] > heap[c] ){
			swap(poz[p], poz[c]);
			swap(heap[p],heap[c]);
			p = c ;
			c = 2*c;
			
		}
		else break;
	}
	c = m; p = m/2;
	while ( p != 0 ) {
		if( heap[c] < heap[p] ){
			swap(poz[p],poz[c]);
			swap( heap[c],heap[p] );
			c = p ; p = p/2;
		}
		else
			break;
	}
	
}
int main () {
	
	fscanf(f,"%d",&NN);
	for ( i = 1 ; i <= NN ; ++i ){
		
		fscanf(f,"%d",&caz);
		switch(caz){
			
		case 1 :{
				
				fscanf(f,"%d",&x);
				poz[++ordine] = x;
				add_heap(x);
				
				break;
			}
		case 2:{
				
				fscanf(f,"%d",&x);
				remove_heap(x);
				
				break;
			}
		case 3:{
				
				fprintf(g,"%d\n",heap[1]);
				
				break;
			}
			
		}
		
	}
	
	fclose(f);
	fclose(g);
	
	return 0;
}