Cod sursa(job #651394)

Utilizator Robert29FMI Tilica Robert Robert29 Data 20 decembrie 2011 10:52:30
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include<stdio.h>
FILE*f=fopen("heapuri.in","r");
FILE*g=fopen("heapuri.out","w");
int t,n,nr,a,x,v[200002],p[200002],h[200002];
void insert (int x)
{
	h[++n]=nr;
	int k=n;
	int key=v[nr];
	while(k>1&&key<v[h[k/2]])
	{
		h[k]=h[k/2];
		p[h[k]]=k;
		k/=2;
		
	}
	h[k]=nr;
	p[n]=k;
}
void erase(int k){
	h[k]=h[n];
	--n;
	p[h[k]]=k;
	if(k>1&&v[h[k]]<v[h[k/2]])
	{
		int key=h[k];
		while(k>1&&v[key]<v[h[k/2]])
		{
			h[k]=h[k/2];
			p[h[k]]=k;
			k/=2;
			
		}
		h[k]=key;
		p[key]=k;
	}
	else
	{
		int son;
		int key=h[k];
		do 
		{
			son=0;
			if(2*k<=n)
			{
				son=2*k;
				if(2*k+1<=n&&v[h[2*k+1]]<v[h[2*k]])
					son=2*k+1;
				if(v[h[son]]>=v[h[k]])
					son=0;	
			}
			
			if(son)
			{
				int aux=h[k];
				h[k]=h[son];
				h[son]=aux;
				p[h[k]]=k;
				p[h[son]]=son;
				k=son;
			}
			
		}
		while(son);
	}
	
	
}
int main() {
	fscanf(f,"%d",&t);
	for(int i=1;i<=t;++i)
	{
		fscanf(f,"%d",&a);
		if(a==3)
			fprintf(g,"%d\n",v[h[1]]);
		else if(a==1)
		{
			fscanf(f,"%d",&v[++nr]);
			insert(v[nr]);
		}
		else
		{
			fscanf(f,"%d",&x);
			erase(p[x]);
		}
	}
	
	
	fclose(g);
	fclose(f);
	return 0;
}