Cod sursa(job #269166)

Utilizator philipPhilip philip Data 2 martie 2009 16:42:26
Problema Cautare binara Scor 60
Compilator fpc Status done
Runda Arhiva educationala Marime 0.93 kb
var f,g:text;
    n,m,i,x,q,y:longint;
    a:array[1..100000] of longint;

procedure citire;
  begin
    assign(f,'cautbin.in');
    reset(f);
    readln(f,n);
    for i:=1 to n do read(f,a[i]);
    readln(f);
    assign(g,'cautbin.out');
    rewrite(g);
  end;

function caut(x,st,dr:longint):longint;
  begin
    m:=(st+dr) div 2;
    if (x=a[m]) or (st=dr) then caut:=m
      else if x>a[m] then caut:=caut(x,m+1,dr)
        else caut:=caut(x,st,m);
  end;

procedure rasp;
  begin
    readln(f,m);
    for i:=1 to m do begin
      readln(f,q,x);
      y:=caut(x,1,n);
      if q=0 then if x=a[y] then begin while a[y+1]=x do inc(y); writeln(g,y); end
        else writeln(g,-1)
          else if q=1 then if a[y]<=x then writeln(g,y)
            else writeln(g,y-1)
              else if a[y]>=x then writeln(g,y)
                else write(g,y+1);
    end;
  end;

begin
  citire;
  rasp;
  close(g);
end.