Cod sursa(job #196619)

Utilizator theratmantheratman theratman Data 27 iunie 2008 15:12:28
Problema Cautare binara Scor 40
Compilator fpc Status done
Runda Arhiva educationala Marime 1.24 kb
var f,g:text;
    a:array[1..100000]of longint;
    x,op,poz,c,st,dr,n,m,i:longint;
begin
assign(f,'cautbin.in');reset(f);
assign(g,'cautbin.out');rewrite(g);
read(f,n);
for i:=1 to n do read(f,a[i]);
read(f,m);
for i:=1 to m do begin
 read(f,op,x);
 if op=0 then begin
  poz:=0;
  st:=1;
  dr:=n;
  while (st<=dr)and(poz=0)do begin
   c:=(st+dr)div 2;
   if x>a[c] then st:=c+1;
   if x<a[c] then dr:=c-1;
   if x=a[c] then poz:=c;
  end;
  if poz<>0 then
   while x=a[poz+1] do inc(poz);
  if poz<>0 then writeln(g,poz)
   else writeln(g,'-1');
 end;
 if op=1 then begin
  poz:=0;
  st:=1;
  dr:=n;
  while (st<=dr)and(poz=0) do begin
   c:=(st+dr) div 2;
   if x<a[c] then dr:=c-1;
   if x>a[c] then st:=c+1;
   if x=a[c] then poz:=c;
  end;
  if poz<>0 then writeln(g,poz)
   else begin
   poz:=dr;
   if a[poz]>x then dec(poz);
   writeln(g,poz);
   end;
 end;
 if op=2 then begin
  poz:=0;
  st:=1;
  dr:=n;
  while (st<=dr)and(poz=0) do begin
   c:=(st+dr) div 2;
   if x<a[c] then dr:=c-1;
   if x>a[c] then st:=c+1;
   if x=a[c] then poz:=c;
  end;
  if poz<>0 then writeln(g,poz)
   else begin
   poz:=st;
   if a[poz]<x then inc(poz);
   writeln(g,poz);
   end;
 end;
end;
close(f);
close(g);
end.