Cod sursa(job #797079)

Utilizator Buzu_Tudor_RoCont vechi Buzu_Tudor_Ro Data 13 octombrie 2012 13:25:37
Problema Heapuri Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 1.92 kb
Program p1;
var fi,fo:text;
    j,t,q,x,n,hp:longint;
    h,valoare,poz:array[0..1 shl 18] of longint;
    b1,b2:array[0..1 shl 18] of char;

Procedure swap(var a:longint; var b:longint);
var aux:longint;
begin
    aux:=a; a:=b; b:=aux;
end;

Procedure sift(k:longint);
var nod:longint;
begin
    nod:=5;
    while nod>0 do
       begin
       nod:=0;
       if 2*k<=hp then begin
                       nod:=2*k;
                       if (2*k+1<=hp) and
                       (valoare[h[nod]]>valoare[h[nod+1]]) then inc(nod);
                       if valoare[h[nod]]>=valoare[h[k]] then nod:=0;
                       end;
       if nod<>0 then begin
                      swap(poz[h[nod]],poz[h[k]]);
                      swap(h[nod],h[k]);
                      k:=nod;
                      end;
       end;
end;

Procedure percolate(k:longint);
begin
    while (k>1) and (valoare[h[k]]<valoare[h[k div 2]])
             do begin
                swap(poz[h[k]],poz[h[k div 2]]);
                swap(h[k],h[k div 2]);
                k:=k div 2;
                end;
end;

Procedure adaug(x:longint);
begin
    n:=n+1; valoare[n]:=x;
    hp:=hp+1; h[hp]:=n;
    poz[n]:=hp;
    percolate(poz[n]);
end;

Procedure sterg(k:longint);
begin
    poz[h[hp]]:=k;
    swap(h[k],h[hp]);
    hp:=hp-1;

    if (k>1) and (valoare[h[k]]<valoare[h[k div 2]]) then percolate(k) else sift(k);

end;

begin
    assign(fi,'heapuri.in'); reset(fi);
    assign(fo,'heapuri.out'); rewrite(fo);
    settextbuf(fi,b1); settextbuf(fo,b2);
    readln(fi,q);  n:=0; hp:=0;
    for j:=1 to q do begin
                     read(fi,t);
                     if t=1 then begin readln(fi,x); adaug(x); end
                else if t=2 then begin readln(fi,x); sterg(poz[x]); end
                else if t=3 then begin readln(fi); writeln(fo,valoare[h[1]]); end;
                     end;
    close(fi); close(fo);
end.