Cod sursa(job #280390)

Utilizator cheery_g1rlHaller Emanuela cheery_g1rl Data 13 martie 2009 12:49:51
Problema Heapuri Scor 10
Compilator fpc Status done
Runda Arhiva educationala Marime 1.63 kb
var lh,aux,n,x,b,j:longint;
    poz,h,a:array[1..200000] of longint;
procedure reconst(i,pp:longint);
   begin
     while (i>1)and(h[i div 2]>h[i]) do
       begin
         aux:=h[i]; h[i]:=h[i div 2]; h[i div 2]:=aux;
         poz[a[i div 2]]:=i;
         aux:=a[i]; a[i]:=a[i div 2]; a[i div 2]:=aux;
         poz[pp]:=i div 2;
         i:=i div 2;
       end;
   end;
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;
                 reconst(lh,lh);
               end
                       else
                         begin
                           readln(b);
                           h[poz[b]]:=h[lh];
                           dec(lh);
                           reconst(poz[b],a[poz[b]]);
                           reconstituire_heap(poz[b],a[poz[b]]);
                         end;
    dec(n);
  end;
close(input); close(output);
end.