Cod sursa(job #929183)

Utilizator Dddarius95Darius-Florentin Neatu Dddarius95 Data 26 martie 2013 21:41:55
Problema Heapuri Scor 0
Compilator fpc Status done
Runda Arhiva educationala Marime 2.05 kb
//fie o multime de numere naturale initial vida.
//Se cere sa se efectueze N operatii asupra acestei multimi, unde operatiile sunt de tipul celor de mai jos:
//operatia de tipul 1: se insereaza elementul x in multime
//operatia de tipul 2: se sterge elementul intrat al x-lea in multime, in ordine cronologica
// operatia de tipul 3: se afiseaza elementul minim din multime

program heapuri;
var v,h,poz:array [1..1 shl 18] of longint;
    n,m,hp,i,op,x:longint;
    f,g:text;
    intrare,iesire:array[1..300000]of char;

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

procedure urca(k:longint);
begin
while (k>1) and (v[h[k]]<v[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 coboara(k:longint);
var nod:longint;
begin
nod:=1;
while nod>0 do
 begin
 nod:=0;
 if 2*k<=hp then
                begin
                nod:=2*k;
                if (2*k+1<=hp) and (v[h[nod]]>v[h[nod+1]]) then inc(nod);
                if v[h[nod]]>=v[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 insert(x:longint);
begin
inc(hp); inc(n); v[n]:=x; h[hp]:=n; poz[n]:=hp;
urca(hp);
end;

procedure delet(k:longint);
begin
poz[h[hp]]:=k; swap(h[k],h[hp]); dec(hp);
if (k>1) and (v[h[k]]<v[h[k div 2]]) then urca(k)
                                     else coboara(k);
end;

begin
assign(f,'heapuri.in');reset(f);settextbuf(f,intrare);
assign(g,'heapuri.out');rewrite(g);settextbuf(g,iesire);
for i:=1 to m do
  begin
  read(f,op);
  if op=1 then begin
               readln(f,x);
               insert(x);
               end
  else
  if op=2 then begin
               readln(f,x);
               delet(poz[x]);
               end
          else begin
               readln(f);
               writeln(g,v[h[1]]);
               end;
  end;
close(f);close(g);
end.