Pagini recente » Cod sursa (job #870447) | Cod sursa (job #3269466) | Cod sursa (job #101965) | Cod sursa (job #913156) | Cod sursa (job #338938)
Cod sursa(job #338938)
#include <cstdio>
#define MaxN 200009
#define t(x) ((x)/2)
#define fs(x) (2*(x))
#define fd(x) (2*(x)+1)
int n,N,L,heap[MaxN],poz[MaxN],A[MaxN],x,o;
void swap(int x,int y)
{
int aux=heap[x];
heap[x]=heap[y];
heap[y]=aux;
}
void urca_heap(int nod)
{
while(nod>1 && A[heap[nod]]<A[heap[t(nod)]])
{
swap(nod,t(nod));
poz[heap[nod]]=nod;
poz[heap[t(nod)]]=t(nod);
nod=t(nod);
}
}
void coboara_heap(int nod)
{
while((fs(nod)<=L && A[heap[nod]]>A[heap[fs(nod)]]) ||
(fd(nod)<=L && A[heap[nod]]>A[heap[fd(nod)]]))
{
if(fd(nod)<=L)
{
if(A[heap[fs(nod)]]<A[heap[fd(nod)]])
{
swap(nod,fs(nod));
poz[heap[nod]]=nod;
poz[heap[fs(nod)]]=fs(nod);
nod=fs(nod);
}
else
{
swap(nod,fd(nod));
poz[heap[nod]]=nod;
poz[heap[fd(nod)]]=fd(nod);
nod=fd(nod);
}
}
else
{
swap(nod,fs(nod));
poz[heap[nod]]=nod;
poz[heap[fs(nod)]]=fs(nod);
nod=fs(nod);
}
}
}
void insert(int nod)
{
N++; L++;
A[N]=nod;
heap[L]=N;
poz[N]=L;
urca_heap(L);
}
void erase(int nod)
{
A[nod]=-1;
urca_heap(poz[nod]);
poz[heap[1]]=0;
heap[1]=heap[L--];
poz[heap[1]]=1;
if(L>1)
coboara_heap(1);
}
int main()
{
freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&o);
if(o==3)
printf("%d\n",A[heap[1]]);
else
{
scanf("%d",&x);
if(o==1)
insert(x);
else
erase(x);
}
}
return 0;
}