Cod sursa(job #1633800)

Utilizator mirelabocsabocsa mirela mirelabocsa Data 6 martie 2016 12:51:03
Problema Heapuri Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 2.15 kb
program mire;
type heap=array[1..200000] of longint;
var f,g:text;
    n,p,cod,va,i,c,d,dd,nr:longint;
    h:heap;
    pz,poz,he:array[1..200000] of longint;
function father(nod:longint):longint;
begin
  father:=nod div 2;
end;
function son_left(nod:longint):longint;
begin
  son_left:=2*nod;
end;
function son_right(nod:longint):longint;
begin
  son_right:=2*nod+1;
end;
procedure percolate(var h:heap; n:longint; k:longint);
var key,aux:longint;
begin
  key:=h[he[k]];
  while(k>1) and (key<h[he[father(k)]]) do
    begin
     aux:=he[k];
      he[k]:=he[father(k)];
      he[father(k)]:=aux;
      poz[he[k]]:=k;
      poz[he[father(k)]]:=father(k);
      k:=father(k);
    end;
  h[he[k]]:=key;
end;
procedure insert(var h:heap; var n:longint; v:longint);
begin
  h[n]:=v;
  percolate(h,n,n);
end;
procedure sift(var h:heap; var n:longint; k:longint);
var son,aux,l,r:longint;
begin
 repeat
   son:=0;
   l:=son_left(k);
   r:=son_right(k);
   if l<=n then
     begin
       son:=l;
       if (r<=n)and (h[he[r]]<h[he[l]]) then
          son:=r;
       if h[he[son]]>=h[he[k]] then
         son:=0;
     end;
   if son<>0 then
     begin
       aux:=he[k];
       he[k]:=he[son];
       he[son]:=aux;
       poz[he[k]]:=k;
       poz[he[son]]:=son;
       k:=son;
     end;
 until son=0;
end;

procedure elimin(var h:heap; var n:longint; k:longint );
begin
  he[k]:=he[n];
  dec(n);
  if (k>1) and (h[he[k]]<h[he[father(k)]])then
       percolate(h,n,k)
  else
        sift(h,n,k);
end;
begin
  assign(f,'heapuri.in'); reset(f);
  assign(g,'heapuri.out'); rewrite(g);
    readln(f,p);
    n:=0; nr:=0;
    for i:=1 to p do
      begin
         read(f,cod);
         if cod=1 then
           begin
           read(f,va);
             inc(n);  inc(nr);
             he[n]:=nr;
             poz[nr]:=n;
             insert(h,n,va);
           end
         else
          if cod=3 then
            writeln(g,h[he[1]])
          else
            begin
               read(f,va);
               dd:=poz[va];
               elimin(h,n,dd);
            end;
      end;
  close(f);
  close(g);
end.