Cod sursa(job #302934)

Utilizator rethosPaicu Alexandru rethos Data 9 aprilie 2009 13:40:26
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <stdio.h>
#define NM 200001
int n;
int heap[NM];
int poz[NM];
int inv[NM];
void hup(int);
void hdown(int);
inline void swap(int x,int y)
{int aux;
 aux=heap[x];
 heap[x]=heap[y];
 heap[y]=aux;
 aux=poz[inv[x]];
 poz[inv[x]]=poz[inv[y]];
 poz[inv[y]]=aux;
 aux=inv[x];
 inv[x]=inv[y];
 inv[y]=aux;
}
void ins(int x,int i)
{n++;
 heap[n]=x;
 poz[i]=n;
 inv[n]=i;
 hup(n);
}
void del(int x)
{int p=poz[x];
 swap(p,n);
 n--;
 if (heap[p]<heap[p/2]) 
	 {hup(p);
	  return;
	 }
 if (heap[p]>heap[2*p]||heap[p]>heap[2*p+1])
	 {hdown(p);
	 }	 
}

int main()
{freopen("heapuri.in","r",stdin);
 freopen("heapuri.out","w",stdout);
 int nr;
 scanf("%d",&nr);
 int i,x,j=0;
 while (nr--)
	 {scanf("%d",&i);
	  switch (i)
		  {case 1:j++;scanf("%d",&x);ins(x,j);break;
		   case 2:scanf("%d",&x);del(x);break;
		   case 3:printf("%d\n",heap[1]);
		  }
	 }
 return 0;
} 
void hup(int k)
{if (k==1) return;
 int t=k/2;
 if (heap[t]>heap[k])
	 {swap(t,k);
	  hup(t);
	 }
}
void hdown(int k)
{int f1=2*k;
 int f2=f1+1;
 if (f1>n) return;
 if (f1==n)
	 {if (heap[k]>heap[f1]) swap(k,f1);
	  return;
	 }
 if (heap[k]<heap[f1]&&heap[k]<heap[f2]) return;	 
 if (heap[f1]<heap[f2])
	 {swap(f1,k);
	  hdown(f1);
	 }
	 else
	 {swap(f2,k);
	  hdown(f2);
	 }
}