Cod sursa(job #1632387)

Utilizator robertadRoxana Rodile robertad Data 6 martie 2016 08:46:56
Problema Heapuri Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 1.82 kb
program heapuri;
var f,g:text;
    h,cro:array[1..200000] of int64;
    n,nr,i,cod,k:int64;
function tata(x:int64):int64;
begin
tata:=x div 2;
end;
function leftson(x:int64):int64;
begin
leftson:=x*2;
end;
function rightson(x:int64):int64;
begin
rightson:=x*2+1;
end;
procedure sift(n,k:int64);
var son,aux:integer;
begin
repeat
son:=0;
if leftson(k)<=n then
begin
son:=leftson(k);
if (rightson(k)<=n) and (h[rightson(k)]>h[leftson(k)]) then
son:=rightson(k);
if h[son]<=h[k] then
son:=0;
end;
if son>0 then
begin
aux:=h[k];
h[k]:=h[son];
h[son]:=aux;
k:=son;
end;
until son=0;
end;
procedure percolate(k:int64);
var key:integer;
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;
procedure insert(n,k:int64);
  begin
    h[n]:=k;
    percolate(n);
  end;
procedure cut(n,k:int64);
  begin
    h[k]:=h[n];
    n:=n-1;
    if ((k > 1) and  (h[k] > h[tata(k)])) then
        percolate(k)
        else
        sift(n,k);
  end;
function search(x:int64):longint;
var i,poz:longint;
begin
  for i:=1 to n do
    if h[i]=x then
               begin
                 poz:=i;
                 break;
               end;
  search:=poz;
end;
begin
assign(f,'heapuri.in');
assign(g,'heapuri.out');
reset(f);
rewrite(g);
readln(f,nr);
n:=0;
while not seekeof(f) do
begin
  read(f,cod);
  if cod=1 then
           begin
             n:=n+1;
             read(f,nr);
             cro[n]:=nr;
             insert(n,nr);
           end
           else
  if cod=2 then
           begin
             read(f,nr);
             k:=search(cro[nr]);
             cut(n,k);
             n:=n-1;
             percolate(n);
           end
           else
           writeln(g,h[1]);
  readln(f);
end;
close(f);
close(g);
end.