Cod sursa(job #393896)

Utilizator mimarcelMoldovan Marcel mimarcel Data 10 februarie 2010 09:47:34
Problema Hashuri Scor 30
Compilator fpc Status done
Runda Arhiva educationala Marime 2.23 kb
//tratez hashurile cu heapuri chiar daca functia de cautare are
//complexitate O(n) la heapuri => timpul de executie nu va fi destul de bun
const maxn=1000000;
type heap=array[1..maxn]of longint;
var h:heap;
    n,i,x,m,p:longint;
    op:byte;

procedure sus(var h:heap;a:longint);
var k,p:longint;
begin
k:=h[a];
p:=a shr 1;
while(a<>1)and(k>h[p])do
  begin
  h[a]:=h[p];
  a:=p;
  p:=a shr 1;
  end;
h[a]:=k;
end;


procedure insert(var h:heap;var x:longint);
begin
inc(m);
h[m]:=x;
sus(h,m);
end;

procedure jos(var h:heap;var a:longint);
var k,f:longint;
begin
k:=h[a];
repeat
if a shl 1>m then break
             else
  begin
  f:=a shl 1;
  if(f+1<=m)and(h[f+1]>h[f])then f:=f+1;
  end;
if h[f]>k then begin
               h[a]:=h[f];
               a:=f;
               end
          else break;
until false;
h[a]:=k;
end;

procedure sterge(var h:heap;var x:longint);
begin
h[x]:=h[m];
dec(m);
if x<>m+1 then if(x<>1)and(h[x]>h[x shr 1])then sus(h,x)
                                           else jos(h,x);
end;

function cautare(var h:heap;p:longint):byte;
begin
if p>m then cautare:=0
       else if h[p]=x then cautare:=1
                      else if cautare(h,p shl 1)=1 then cautare:=1
                                                   else
                              if cautare(h,p shl 1+1)=1 then cautare:=1
                                                        else cautare:=0;
end;

function poz(var h:heap;p:longint):longint;
var a:longint;
begin
if p>m then poz:=0
       else
  if h[p]=x then poz:=p
            else begin
                 if(p shl 1<=m)and(x<=h[p shl 1])then a:=poz(h,p shl 1)
                                                 else a:=0;
                 if(a=0)and(p shl 1+1<=m)and(x<=h[p shl 1+1])then a:=poz(h,p shl 1+1);
                 poz:=a;
                 end;
end;

begin
assign(input,'hashuri.in');
reset(input);
assign(output,'hashuri.out');
rewrite(output);
readln(n);
for i:=1 to n do
  begin
  readln(op,x);
  case op of
    1:if cautare(h,1)=0 then insert(h,x);
    2:begin
      p:=poz(h,1);
      if p<>0 then sterge(h,p);
      end;
    3:writeln(cautare(h,1));
    end;
  end;
close(output);
close(input);
end.