Cod sursa(job #365615)

Utilizator 05_YohnE1 La5c01 05_Yohn Data 19 noiembrie 2009 14:20:49
Problema Heapuri Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 1.28 kb
var heap,v,pos:array[1..100]of longint;
m,n,k,x:longint;
f:byte;

procedure schimb(x,y:longint);
var aux:longint;
begin
aux:=heap[x];
heap[x]:=heap[y];
heap[y]:=aux;
pos[heap[x]]:=x;
pos[heap[y]]:=y;
end;


procedure sus(x:longint);
begin
while (x shr 1<>0)and(heap[x shr 1]>heap[x])do begin
   schimb(x,x shr 1);
   x:=x shr 1;
   end;
end;


procedure adaug(x:longint);
begin
inc(n);
inc(k);
v[n]:=x;   {valoare}
heap[k]:=n;      {cheie / id}
pos[n]:=k;      {pozitie in arbore= nr noduri la un mom dat}
sus(k);
end;

procedure jos(x:longint);
var y:longint;
begin
y:=0;
while x<>y do begin
      y:=x;
      if (y*2<=k)and(v[heap[x]]>v[heap[y*2]]) then x:=y*2;
      if (y*2+1<=k)and(v[heap[x]]>v[heap[2*y+1]]) then x:=y*2+1;
      schimb(x,y);
end;
end;

begin
assign(input,'heapuri.in');reset(input);
assign(output,'heapuri.out');rewrite(output);
read(m);
n:=0;k:=0;
while m<>0 do begin
read(f);
case f of
     1:begin
       read(x);
       adaug(x);
       end;
     2:begin
       read(x);
       v[x]:=-1;
       sus(pos[x]);
       pos[heap[1]]:=0;
       heap[1]:=heap[k];
       dec(k);
       pos[heap[1]]:=1;
       if k>1 then jos(1);
       end;
     else writeln(v[heap[1]]);
     end;
dec(m);
end;
close(output);
end.