Pagini recente » Cod sursa (job #354088) | Cod sursa (job #2944327) | Cod sursa (job #2106616) | Cod sursa (job #2737738) | Cod sursa (job #338880)
Cod sursa(job #338880)
#include <cstdio>
#include <vector>
#define MaxN 200009
#define fs(x) (2*(x))
#define fd(x) (2*(x)+1)
int heap[MaxN],poz[MaxN],O[MaxN],n,x,o,N;
void swap(int x,int y)
{
int aux=heap[x];
heap[x]=heap[y];
heap[y]=aux;
}
void urca_heap(int nod)
{
int tata,aux;
while(nod>1)
{
tata=nod/2;
if(heap[tata]>heap[nod])
{
swap(tata,nod);
aux=O[tata]; O[tata]=O[nod]; O[nod]=aux;
aux=poz[O[tata]]; poz[O[tata]]=poz[O[nod]]; poz[O[nod]]=aux;
nod=tata;
}
else
nod=1;
}
}
void insert(int nod)
{
N++;
heap[N]=nod;
poz[N]=N;
O[N]=N;
urca_heap(N);
}
void coboara_heap(int nod)
{
int nodi,aux;
for(;;)
{
nodi=nod;
if(fs(nod)<=N && heap[fs(nod)]<heap[nodi])
nodi=fs(nod);
if(fd(nod)<=N && heap[fd(nod)]<heap[nodi])
nodi=fd(nod);
if(nod>N || nodi==nod)
return;
swap(nodi,nod);
aux=O[nodi]; O[nodi]=O[nod]; O[nod]=aux;
aux=poz[O[nodi]]; poz[O[nodi]]=poz[O[nod]]; poz[O[nod]]=aux;
}
}
void erase(int p)
{
int nod=poz[p];
heap[nod]=heap[N];
O[nod]=O[N];
poz[O[nod]]=poz[O[N]];
N--;
if(heap[nod]<heap[nod/2])
urca_heap(nod);
else
if(heap[nod]>heap[nod*2] || heap[nod]>heap[nod*2+1])
coboara_heap(nod);
}
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==1)
{
scanf("%d",&x);
insert(x);
}
else
if(o==2)
{
scanf("%d",&x);
erase(x);
}
else
printf("%d\n",heap[1]);
}
return 0;
}