Cod sursa(job #496049)

Utilizator chiar_nimeninimeni chiar_nimeni Data 27 octombrie 2010 17:26:07
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include<stdio.h>
int n,i,x,a[200010],l,b[200100],q,j,w;
bool ok;
void swap(int k, int t){
	int x;
	x=a[t];
	a[t]=a[k];
	a[k]=x;
}

void heapup(int k){
	int t;
	if (k<=0) return;
	t=k/2;
	if (a[k]<a[t]){
		swap(k,t);
		heapup(t);
	}
}

void buildh(int k){
	int i;
	for (i=1; i<k; i++) heapup(i);
}

void heapdown(int r, int k){
	int st,dr,i;
	if (2*r<=k){
		st=a[2*r];
		if (2*r+1<=k) dr=a[2*r+1];
		else dr=st-1;
		if (st>dr) i=2*r+1;
		else i=2*r;
		if (a[r]>a[i]){
			swap(r,i);
			heapdown(i,k);
		}
	}
}

void heapsort(int k){
	while (k>0){
		swap(0,k);
		k--;
		heapdown(0,k);
	}
}

int main(){
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	scanf("%d",&n);
	l=0;
	for (i=1; i<=n; i++)
	{
		scanf ("%d",&q);
		if (q==1)
		{
			l++;
			scanf ("%d",&a[l]);
			b[l]=a[l];
			heapup (l);
		}
		else if (q==2)
		{
			scanf ("%d",&w);
			x=b[w];
			ok=true;
			j=0;
			while (ok==true)
			{
				j++;
				if (a[j]==x)
				{
					ok=false;
					a[j]=a[l];
					l--;
					heapdown (j,l);
				}
			}
		}
		else if (q==3)
		{
			printf ("%d\n",a[1]);
		}
	}
	/*buildh(n);
	heapsort(n-1);
	for (i=1; i<=n; i++)
		printf("%d ",a[i]);*/
	return(0);
}