Cod sursa(job #269211)

Utilizator philipPhilip philip Data 2 martie 2009 17:41:34
Problema Cautare binara Scor 60
Compilator fpc Status done
Runda Arhiva educationala Marime 1.26 kb
var f,g:text;
    n,m,i,x,q,y:longint;
    a:array[0..100001] 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;

function caut1(x,st,dr:longint):longint;
  begin
    while st<=dr do begin
      m:=(st+dr) div 2;
      if x<a[m] then dr:=m-1
        else begin caut1:=m; st:=m+1; end;
    end;
  end;

function caut2(x,st,dr:longint):longint;
  begin
    while st<=dr do begin
      m:=(st+dr) div 2;
      if x<=a[m] then begin caut2:=m; dr:=m-1; end
        else begin st:=m+1; end;
    end;
  end;

procedure rasp;
  begin
    readln(f,m);
    for i:=1 to m do begin
      readln(f,q,x);

      case q of
        0: begin y:=caut(x,1,n); if x=a[y] then begin while a[y+1]=x do inc(y); writeln(g,y); end
        else writeln(g,-1); end;
        1: writeln(g,caut1(x,1,n));
        2: writeln(g,caut2(x,1,n));
      end;
    end;
    close(g);
  end;

begin
  citire;
  rasp;
end.