Cod sursa(job #694808)

Utilizator i.anna_mIlusca Ana-Maria i.anna_m Data 28 februarie 2012 01:29:41
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
//frunza
#include<stdio.h>
int h[200003][2],n,v[200002],kul=1;
FILE *f,*g;
void percolate(int k)
{
	int aux,auy;
	while(k/2>0 && h[k/2][0]>h[k][0])
	{
		aux=h[k][0];
		auy=h[k][1];
		v[h[k][1]]=k/2;
		v[h[k/2][1]]=k;
		h[k][0]=h[k/2][0];
		h[k][1]=h[k/2][1];
		h[k/2][1]=auy;
		h[k/2][0]=aux;
		k=k/2;
	}
}
void sift(int k)
{
	//se alege cel mai mic fiu, si daca asta nu e ok, se interschimba, si k ia valoarea lui son;
	int aux,auy,son;
	do
	{
		son=0;
		if(k*2<=n)
		{
			son=k*2;
			if(k*2+1<=n && h[k*2+1][0]<h[k*2][0])
				son=k*2+1;
		}//am ales fiul cel mai mic;
		if(h[son][0]>=h[k][0])
			son=0;//deci e ok;
		if(son)//daca nu e ok;
		{
			aux=h[k][0];
			auy=h[k][1];
			v[h[k][1]]=son;
			v[h[son][1]]=k;
			h[k][1]=h[son][1];
			h[son][1]=auy;
			h[k][0]=h[son][0];
			h[son][0]=aux;
			k=son;
		}
	}while(son);
}
void op2(int k)
{
	h[k][0]=h[n][0];
	h[k][1]=h[n][1];
	v[h[n][1]]=k;
	v[h[k][1]]=0;
	n--;
	if(h[k][0]<h[k/2][0] && k/2>0)
		percolate(k);
	else if((h[k][0]>h[k*2][0] && k*2<=n) || (h[k][0]>h[k*2+1][0] && k*2+1<=n))
		sift(k);
}
int main()
{
	int m,t,x,l=0;
	register int i;
	f=fopen("heapuri.in","r");
	g=fopen("heapuri.out","w");
	fscanf(f,"%d",&m);
	for(i=0;i<m;i++)
	{
		fscanf(f,"%d",&t);
		if(t==1)
		{
			fscanf(f,"%d",&x);
			++n;
			h[n][0]=x;
			h[n][1]=kul;
			v[kul]=n;
			++kul;
			if(l==0)
				l=1;
			else			
				percolate(n);
		}
		if(t==2)
		{
			fscanf(f,"%d",&x);
			op2(v[x]);
		}
		if(t==3)
			fprintf(g,"%d ",h[1][0]);
	}
	fclose(f);
	fclose(g);
	return 0;
}