Cod sursa(job #680397)

Utilizator andreifirstCioara Andrei Ioan andreifirst Data 15 februarie 2012 15:57:42
Problema Cerere Scor 0
Compilator fpc Status done
Runda Arhiva de probleme Marime 1.98 kb
var v:array [0..20, 0..100000] of longint;
    w1:array[1..100000] of longint;
    r:array [1..100000] of longint;
    i, j, n, m, x, y, z, t:longint;
    f, g:text;
    ok:boolean;
    c:char;
    buf1, buf2:array [1.. 1 shl 17] of char;

procedure citire1;
  begin
  i:=0;
  x:=0;
  while not eoln (f) do
    begin
    read (f, c);
    if (ord(c)>=48) and (ord(c)<=57) then begin x:=x*10+ord(c)-48; end
                                     else begin inc (i); w1[i]:=x; x:=0; end;
    end;
  inc (i); w1[i]:=x;
  end;

procedure citire2;
  begin
  while not eof (f) do
    begin
    x:=0; y:=0;
    read (f, c);
    while (ord(c)>=48) and (ord(c)<=57) do begin x:=x*10+ord(c)-48; read (f, c); end;
    read (f, c);
    while (ord(c)>=48) and (ord(c)<=57) do begin y:=y*10+ord(c)-48; read (f, c); end;
    v[1, y]:=x;
//    readln (f);
    end;
  end;


function cauta (fp:longint):longint;
var fy, fx, fj:longint;
  begin

  if w1[fp]=0 then cauta:=0 else
    begin
    if r[fp]<>0 then cauta:=r[fp] else
      begin
      fx:=fp; fy:=w1[fp];

      fj:=1;
      while (fx<>0) and (fy<>0) do
        begin
        while fy mod 2 = 0 do
          begin
          fy := fy div 2;
          inc (fj);
          end;

        fx:=v[fj, fx];
        fy:=fy div 2; inc (fj);
        end;

      r[fp]:=1+cauta(fx);
      cauta:=r[fp];
      end;
    end;
  end;

begin
assign (f, 'cerere.in'); settextbuf (f, buf1); reset (f);
assign (g, 'cerere.out'); settextbuf (g, buf2); rewrite (g);

readln (f, n);

// citire manuala
citire1;
//readln (f);
citire2;


// initializarea dinamicii
ok:=true; i:=1;
while ok do
  begin
  ok:=false;
  for j := 1 to n do
    begin
    if v[i, j]<>0 then
      begin
      v[i+1, j]:=v[i, v[i, j]];
      if v[i+1, j] <> 0 then ok:=true;
      end;
    end;

  inc (i);
  end;

for i := 1 to n do if r[i]=0 then r[i]:= cauta(i);

for i := 1 to n do write (g, r[i], ' ');
close (f); close (g);
end.