Pagini recente » Cod sursa (job #14497) | Cod sursa (job #3261890) | Cod sursa (job #3234928) | Cod sursa (job #951449) | Cod sursa (job #501043)
Cod sursa(job #501043)
#include <stdio.h>
#define nmax 200010
// Pos[x] - pozitia in heap al x-ulea intrat
// ORD[x] - pozitia in vectorul Pos al x-ulea element al heapului
// NR - nr elemente din pos
int Heap[nmax], ORD[nmax], Pos[nmax];
int NR, L;
void precolate(int x)
{
int aux;
while((x>>1) && Heap[(x>>1)] > Heap[x])
{
aux = Heap[(x>>1)];
Heap[(x>>1)] = Heap[x];
Heap[x] = aux;
Pos[ORD[x]] = (x>>1);
Pos[ORD[(x>>1)]] = x;
aux = ORD[x];
ORD[x] = ORD[(x>>1)];
ORD[(x>>1)] = aux;
x = (x>>1);
}
}
void sift(int x)
{
int son, aux;
do
{
son = 0;
if((x<<1) <= L)
{
if((x<<1) + 1 <= L)
if(Heap[(x<<1)] < Heap[(x<<1) + 1])
son = (x<<1);
else
son = (x<<1) + 1;
else
son = (x<<1);
}
if(son && Heap[x] > Heap[son])
{
aux = Heap[x];
Heap[x] = Heap[son];
Heap[son] = aux;
Pos[ORD[x]] = son;
Pos[ORD[son]] = x;
aux = ORD[x];
ORD[x] = ORD[son];
ORD[son] = aux;
x = son;
}
}while (son);
}
void ajustate(int x)
{
if(x && Heap[x] < Heap[(x>>1)])
precolate(x);
else
sift(x);
}
int main ()
{
freopen ("heapuri.in","r",stdin);
freopen ("heapuri.out","w",stdout);
int N, op, x;
scanf ("%d",&N);
while(N--)
{
scanf("%d",&op);
if(op == 3)
printf("%d\n",Heap[1]);
else
{
scanf("%d",&x);
if (op == 1)
{
NR++; L++;
Pos[NR] = L;
ORD[L] = NR;
Heap[L] = x;
precolate(L);
}
else
{
Heap[Pos[x]] = Heap[L];
Pos[ORD[L]] = Pos[x];
ORD[Pos[x]] = ORD[L];
L--;
ajustate(Pos[x]);
}
}
}
return 0;
}