Cod sursa(job #792098)

Utilizator Alexxino7Alexandru Popescu Alexxino7 Data 26 septembrie 2012 14:45:04
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include<algorithm>
#include<fstream>
using namespace std;
#define Maxim 200005

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

int N,A[Maxim],Heap[Maxim],Poz[Maxim],NR,Lg;

void move_up(int X,int Max){
	while(X/2 && A[Heap[X]]<A[Heap[X/2]]){
		swap(Heap[X],Heap[X/2]);
		Poz[Heap[X]]=X;
		Poz[Heap[X/2]]=X/2;
		X/=2;
	}
}

void move_down(int X,int Max){
	int son;
	do{
		son=X;
		if(2*son<=Max && A[Heap[X]]>A[Heap[2*son]])
			X=2*son;
		if(2*son+1<=Max && A[Heap[X]]>A[Heap[2*son+1]])
			X=2*son+1;
		
		swap(Heap[X],Heap[son]);
		Poz[Heap[X]]=X;
		Poz[Heap[son]]=son;
		
	}while(son!=X);
}

int main(){
	
	fin>>N;
	
	int pos,x,y;
	for(int i=1; i<=N; i++){
		fin>>x;
		
		if(x==1){
			fin>>y;
			
			NR++,Lg++;
			A[NR]=y;
			Heap[Lg]=NR;
			Poz[NR]=Lg;
			
			move_up(Lg,Lg);
		}
		
		if(x==2){
			fin>>y;
			pos=Poz[y];
			if(pos!=Lg){
				Heap[pos]=Heap[Lg];
				Poz[Heap[pos]]=pos;
				Poz[y]=-1;
				Heap[Lg--]=0;
				
				if(pos/2 && A[Heap[pos]]<A[Heap[pos/2]])
					move_up(pos,Lg);
				else
					move_down(pos,Lg);
			}
			else{
				Heap[Lg]=0;
				Lg--;
				Poz[y]=-1;
			}
		}
		if(x==3){
			fout<<A[Heap[1]]<<"\n";
		}
	}
	
	fout.close();
	fin.close();
	return 0;
}