Cod sursa(job #401359)

Utilizator nickyyLal Daniel Emanuel nickyy Data 22 februarie 2010 19:54:17
Problema Cautare binara Scor 60
Compilator fpc Status done
Runda Arhiva educationala Marime 0.84 kb
const infile='cautbin.in';
  outfile='cautbin.out';
  maxnm=100000;
var v:array[1..maxnm]of longint;
  n,m,x,i,step,lg:longint;
  op:0..2;
  fi,fo:text;

begin
 assign(fi,infile); reset(fi);
 assign(fo,outfile); rewrite(fo);
 readln(fi,n); for i:=1 to n do read(fi,v[i]);
 step:=1; while(step<n)do step:=step shl 1;
 readln(fi,m);
 while(m>0)do begin
   readln(fi,op,x);
   if(op<2)then begin
     i:=0; lg:=step;
     while(lg<>0)do begin
       if(i+lg<=n)and(v[i+lg]<=x)then inc(i,lg);
       lg:=lg shr 1;
       end;
     if(op=0)and(v[i]<>x)then writeln(fo,-1)
       else writeln(fo,i)
     end
   else begin
     i:=n; lg:=step;
     while(lg<>0)do begin
       if(i-lg>0)and(v[i-lg]>=x)then dec(i,lg);
       lg:=lg shr 1;
       end;
     writeln(fo,i);
     end;
   dec(m);
   end;
 close(fi); close(fo);
end.