Cod sursa(job #929889)

Utilizator andrei_toaderToader Andrei Sorin andrei_toader Data 27 martie 2013 12:35:03
Problema Heapuri Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 2.01 kb
program heapuri;
type heap=array[1..200000] of longint;
var f,g:text;
    n,i,x,y,crcontor:longint;
    h:heap;
    bufin,bufout:array[1..65000] of byte;
    cr:array[1..200000] of longint;
    indice: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 inserare (var h:heap; nod:longint);
var  val,k:longint;
begin
 val:=h[nod];
 k:=nod;
 while (k>1) and (val<h[tata(k)]) do
 begin
  h[k]:=h[tata(k)];
  k:=tata(k);
 end;
 h[k]:=val;
end;

procedure shift (var h:heap; nod:longint);
var fiu:longint;
begin
 repeat
  if fiu_stang(nod)<=n then
  begin
   fiu:=fiu_stang(nod);
  if (fiu_drept(nod)<=n) and (h[fiu_drept(nod)]<h[fiu_stang(nod)]) then
   fiu:=fiu_drept(nod);
  if h[fiu]>=h[nod] then
   fiu:=0;
  end;
 if fiu<>0 then
 begin
  interschimba(h[nod],h[fiu]);
  nod:=fiu;
 end;
 until fiu=0;
end;
procedure stergere (var h:heap;var n:longint; k:longint);
begin
 h[k]:=h[n];//pun ultimul element din heap in locul celui pe care il elimin
 if (k>1) and (h[k]<h[tata(k)])then
   inserare(h,k)
 else
  shift(h,k);
end;

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

begin
 assign (f,'heapuri.in'); reset (f);
 assign (g,'heapuri.out'); rewrite (G);
 settextbuf (f,bufin);
 settextbuf (g,bufout);
 readln (f,n);
 crcontor:=0;
 for i:=1 to n do
 begin
 read (f,x);
 if x=1 then
 begin
  read (f,y);
  inc(crcontor);
  cr[crcontor]:=y;
  inc(n); h[n]:=y;
  inserare (h,n);
 end
 else
  if x=2 then
  begin
   read (f,y);
   indice:=cr[y];
   indice:=cauta(indice);
   stergere(h,n,indice);
  end
  else
  begin
   writeln (g,h[1]);
  end;
 end;
 close (f); close (G);
end.