Cod sursa(job #410048)

Utilizator hungntnktpHungntnktp hungntnktp Data 4 martie 2010 05:51:14
Problema Heapuri Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 1.56 kb
{DINH QUANG DAT TIN 07-10}
{HEAPURI}
CONST
 TFI='heapuri.in';
 TFO='heapuri.out';
 MAX=200000;
TYPE
 arr1int=array[0..MAX] of longint;
VAR
 fi,fo:text;
 task,i,cnt,v,res,nheap,n:longint;
 heap,pos,a:arr1int;

PROCEDURE       swap(var u,v:longint);
var
 tg:longint;
begin
 tg:=u;
 u:=v;
 v:=tg;
end;

PROCEDURE       upheap(child:longint);
var
 parent:longint;
begin
 parent:= child div 2;
 while (parent>0) and (a[heap[parent]]>a[heap[child]]) do
  begin
   swap(heap[parent],heap[child]);
   pos[heap[parent]]:=parent;
   pos[heap[child]]:=child;
   child:=parent;
   parent:= child div 2;
  end;
end;

PROCEDURE       downheap(r:longint);
var
 c:longint;
begin
 while r*2<=nheap do
  begin
   c:=r*2;
   if (c<nheap) and (a[heap[c]]>a[heap[c+1]]) then inc(c);
   if a[heap[c]]>=a[heap[r]] then break;
   swap(heap[c],heap[r]);
   pos[heap[c]]:=c;
   pos[heap[r]]:=r;
   r:=c;
  end;
end;

PROCEDURE       push(u:longint);
begin
 inc(nheap);
 pos[u]:=nheap;
 heap[nheap]:=u;
 upheap(nheap);
end;

PROCEDURE       pop(v:longint);
var
 u:longint;
begin
 u:=pos[v];
 heap[u]:=heap[nheap];
 pos[heap[nheap]]:=u;
 downheap(u);
end;

BEGIN
 assign(fi,tfi);reset(fi);
 assign(fo,tfo);rewrite(fo);
  read(fi,n);
  for i:= 1 to n do
   begin
    read(fi,task);
    case task of
     1:
      begin
       inc(cnt);
       read(fi,a[cnt]);
       push(cnt);
      end;
     2:
      begin
       read(fi,v);
       pop(v);
      end;
     3: writeln(fo,a[heap[1]]);
    end;
   end;
 close(fo);
 close(fi);
END.