Pagini recente » Cod sursa (job #2391874) | Cod sursa (job #61179) | Cod sursa (job #463336) | Cod sursa (job #1264786) | Cod sursa (job #694808)
Cod sursa(job #694808)
//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;
}