Cod sursa(job #108683)

Utilizator h_istvanHevele Istvan h_istvan Data 23 noiembrie 2007 16:05:30
Problema Stramosi Scor 0
Compilator fpc Status done
Runda Arhiva de probleme Marime 1.11 kb
program stramosi;
var f,fout:text;
    n,m,i,j,a,b:longint;
    v:array[1..1000,1..10] of longint;
    control:boolean;

procedure log(a:longint;var b,h:longint);
begin
     h:=1;
     b:=0;
     while(2*h <= a) do
     begin
          h:=2*h;
          b:=b+1;
     end;
end;              +

function os(x,r:longint):longint;
var a,h,k:longint;
begin
     log(r,a,h);
     k:=v[x,a+1];
     r:=r-h;
     if(r = 0) then os:=k
     else if(k > 0) then os:=os(k,r)
                    else os:=0;
end;

begin
     assign(f,'stramosi.in');
     reset(f);
     readln(f,n,m);
     for i:=1 to n do read(f,v[i,1]);
     readln(f);

     control:=true;
     j:=1;
     while(control) do
     begin
          j:=j+1;
          control:=false;
          for i:=1 to n do
          begin
              v[i,j]:=v[v[i,j-1],j-1];
              if(v[i,j] > 0) then control:=true;
          end;
     end;
     assign(fout,'stramosi.out');
     rewrite(fout);
     for i:=1 to m do
     begin
          readln(f,a,b);
          writeln(fout,os(a,b));
     end;
     close(fout);
     close(f);
end.