Cod sursa(job #931043)

Utilizator andrei_toaderToader Andrei Sorin andrei_toader Data 27 martie 2013 22:46:59
Problema Heapuri Scor 10
Compilator fpc Status done
Runda Arhiva educationala Marime 2.02 kb
program heapuri;
type heap=array[1..200000] of longint;
var f,g:text;
    h:array[1..200000] of longint;
    ordine:array[1..200000] of longint;
    bufin,bufout:array[1..65000] of byte;
    n,m,i:longint;
    key,val:longint;
    pozitie:longint;

function tata (nod:longint):longint;
begin
 tata:=nod div 2;
end;

function fiu_stang (nod:longint):longint;
begin
 fiu_stang:=2*nod;
end;

function fiu_drept (nod:longint):longint;
begin
 fiu_drept:=2*nod+1;
end;

procedure interschimba (var a,b:longint);
var aux:longint;
begin
 aux:=a; a:=b; b:=aux;
end;

procedure percolate (var h:heap; k:longint);
var key:longint;
begin
 key:=h[k];
 while (k>1) and (key<h[tata(k)]) do
 begin
  h[k]:=h[tata(k)];
  k:=tata(k);
 end;
 h[k]:=key;
end;

function cauta_pozitie (nod:longint):longint;
var i:longint;
begin
 for i:=1 to n do
  if h[i]=nod then
  begin
   cauta_pozitie:=i; break;
  end;
end;

procedure sift(var h:heap; k:longint);
var fiu:longint;
begin
 repeat
  fiu:=0;
  if fiu_stang(k)<=n then
  begin
   fiu:=fiu_stang(k);
   if (fiu_drept(k)<=n) and (h[fiu_drept(k)]<h[fiu_stang(k)]) then
    fiu:=fiu_drept(k);
   if h[fiu]>h[k] then
    fiu:=0;
  end;
  if fiu<>0 then
  begin
   interschimba(h[k],h[fiu]);
   k:=fiu;
  end;
  until fiu=0;
end;

procedure stergere(var h:heap; k:longint);
begin
 h[k]:=h[n];
 dec(n);
 if (k>1) and (h[k]<h[tata(k)]) then
  percolate (h,k)
 else
  sift(h,k);
end;




begin
 assign (f,'heapuri.in'); reset (F);
 assign (g,'heapuri.out'); rewrite (G);
 settextbuf (f,bufin);
 settextbuf (g,bufout);
 readln (f,m);
 n:=0;
 for i:=1 to  m do
 begin
    read (f,key);
    if key=1 then
    begin
     inc(n);
     read (f,val);
     h[n]:=val;
     ordine[n]:=val;
     percolate (h,n);
    end
   else
    if key=2 then
    begin
     read (f,val);
     pozitie:=cauta_pozitie(ordine[val]);
     stergere(h,pozitie);
    end
    else
    begin
      writeln (g,h[1]);
    end;
 end;
 close (f); close (G);
end.