Pagini recente » Cod sursa (job #908962) | Cod sursa (job #1480118) | Cod sursa (job #896854) | Cod sursa (job #1106338) | Cod sursa (job #486715)
Cod sursa(job #486715)
#include<stdio.h>
#define NMAX 200001
int n,cont=0,ind_order,order[NMAX];
struct H
{
int val;
int order;
}heap[NMAX],aux;
int left_son(int x)
{
return x*2;
}
int right_son(int x)
{
return x*2+1;
}
int father(int x)
{
return x/2;
}
void sift(int x)
{
int son;
do
{
son = 0;
if(left_son(x) <= cont )
{
son = left_son(x);
if(right_son(x) <= cont && heap[right_son(x)].val < heap[left_son(x)].val)
{
son = right_son(x);
}
if(heap[son].val >= heap[x].val)
son = 0;
}
if(son)
{
order[ heap[x].order ] = son;
order[ heap[son].order ] = x;
aux = heap[x];
heap[x] = heap[son];
heap[son] = aux;
x = son;
}
}
while(son);
}
void percolate(int x)
{
while(father(x) > 0 && heap[father(x)].val > heap[x].val)
{
order[ heap[father(x)].order ] = x;
order[ heap[x].order ] = father(x);
aux = heap[father(x)];
heap[father(x)] = heap[x];
heap[x] = aux;
x = father(x);
}
}
void insert(int x)
{
heap[++cont].val = x;
heap[cont].order = ++ind_order;
order[ind_order] = cont;
percolate(cont);
}
void cut(int x)
{
x = order[x];
order[ heap[cont].order ] = x;
order[ heap[x].order ] = -1;
heap[x] = heap[cont];
heap[cont--].val = 0;
if(x > 1 && heap[father(x)].val > heap[x].val)
percolate(x);
else
sift(x);
}
int main()
{
FILE*g = fopen("heapuri.out","w");
FILE*f = fopen("heapuri.in","r");
fscanf(f,"%d",&n);
int i=1,tip,x;
for(;i<=n;++i)
{
fscanf(f,"%d",&tip);
if(tip == 1)
{
fscanf(f,"%d",&x);
insert(x);
}
if(tip == 2)
{
fscanf(f,"%d",&x);
cut(x);
}
if(tip == 3)
fprintf(g,"%d\n",heap[1].val);
}
fclose(f);
fclose(g);
return 0;
}