Cod sursa(job #247445)

Utilizator belgun_adrianBelgun Dimitri Adrian belgun_adrian Data 23 ianuarie 2009 00:19:33
Problema Heapuri Scor 20
Compilator fpc Status done
Runda Arhiva educationala Marime 2.48 kb
// Arhiva educationala - Heapuri
// tata = fiu shr 1
// fiu_st = tata shl 1
// fiu_dr = tata shl 1 + 1

type    elem            = record inf, nr: longint; end;

var     nr,c,x,n,m,i    : longint;
        f,g             : text;
        heap            : array [1..200000] of elem;
        pos             : array [1..200000] of longint;



// corecteaza heapul in sus
procedure       CorrUpH (poz:longint);
var             t       : elem;
begin
t := heap[poz];
while (poz>1) and (t.inf < heap[poz shr 1].inf) do
        begin
        heap[poz] := heap [poz shr 1];
        pos [heap[poz].nr] :=  poz;
        poz := poz shr 1;
        end;
heap[poz] := t;
pos [heap[poz].nr] := poz;
end;


// corecteaza heapul in jos
procedure       CorrDownH (poz:longint);
var             fiu,fs,fd     :longint;
                t             :elem;
begin
repeat
        fiu := 0;
        fs  := poz shl 1;
        //fd:= poz shr 1 + 1;
        fd  := fs + 1;
        //alegem fiul cel mic
        if (fs <= n) then
           begin
           fiu := fs;
           if (fd <= n) and (heap[fs].inf > heap[fd].inf) then
               fiu := fd;
           if (heap[fiu].inf >= heap [poz].inf) then
               fiu:=0;
           end;
        if (fiu<>0)  then
           begin
           //swap (poz, fiu)
           t := heap [poz];
           heap [poz] := heap [fiu];
           heap [fiu] := t;
           pos [heap[poz].nr] := poz;
           pos [heap[fiu].nr] := fiu;
           end;
until   fiu  = 0;
end;

//sterge elementul de pe pozitia poz din heap
// interschimbandu-l cu ultimul elem
// si apoi corectand heapul.
procedure       Delete    (poz:longint);
begin
pos  [heap[poz].nr]:= -1;
heap [poz] := heap [n];
dec  (n);

if (poz>1) and (heap[poz].inf < heap[poz shr 1].inf) then
        CorrUpH  (poz)
else    CorrDownH(poz);
end;


begin
assign  (f, 'heapuri.in');
assign  (g, 'heapuri.out');
reset   (f);
rewrite (g);

readln  (f, nr);
n := 0;
m := 0;
for i:=1 to nr do
    begin
    read   (f,c);
    case c of
        1: begin
           read    (f, x);
           inc     (n);
           inc     (m);
           heap[n].inf := x;
           heap[n].nr  := m;
           CorrUpH(n);
           end;
        2: begin
           read    (f, x);
           //if pos[x]<>0 then
           delete  (pos[x]);
           end;
        3: writeln (g, heap[1].inf);
    end;
    readln (f);
    end;

close   (f);
close   (g);
end.