Cod sursa(job #280287)

Utilizator cheery_g1rlHaller Emanuela cheery_g1rl Data 13 martie 2009 12:15:37
Problema Heapuri Scor 10
Compilator fpc Status done
Runda Arhiva educationala Marime 1.32 kb
var lh,aux,n,x,b,j:longint;
    poz,h,a:array[1..200000] of longint;
procedure reconstituire_heap(i,pp:longint);
   var s,d,min:longint;
   begin
     s:=2*i; d:=2*i+1; min:=i;
     if (s<=lh)and(h[s]<h[min]) then min:=s;
     if (d<=lh)and(h[d]<h[min]) then min:=d;
     if min<>i then
       begin
         aux:=h[i]; h[i]:=h[min]; h[min]:=aux;
         poz[pp]:=min; poz[a[min]]:=i;
         aux:=a[i]; a[i]:=a[min]; a[min]:=aux;
         reconstituire_heap(min,pp);
       end;
   end;
begin
assign(input,'heapuri.in'); reset(input);
assign(output,'heapuri.out'); rewrite(output);
readln(n);
lh:=0;
while (n>=1) do
  begin
    read(x);
    if x=3 then begin writeln(h[1]); readln; end
           else if x=1 then
               begin
                 readln(b);
                 inc(lh);
                 h[lh]:=b;
                 poz[lh]:=lh;
                 a[lh]:=lh;
                 for j:=lh div 2 downto 1 do
                 reconstituire_heap(j,a[j]);
               end
                       else
                         begin
                           readln(b);
                           h[poz[b]]:=h[lh];
                           dec(lh);
                           reconstituire_heap(poz[b],a[poz[b]]);
                         end;
    dec(n);
  end;
close(input); close(output);
end.