Cod sursa(job #912077)

Utilizator Dddarius95Darius-Florentin Neatu Dddarius95 Data 12 martie 2013 06:13:50
Problema BFS - Parcurgere in latime Scor 100
Compilator fpc Status done
Runda Arhiva educationala Marime 0.92 kb
program bfs;
var f,g:text;
    n,m,i,x,y,ps,pi:longint;
    a:array of array of longint;
    viz:array[1..100000] of 0..1;
    cd:array[1..100000] of longint;
    bufin,bufout:array[1..65000] of byte;
    d:array[1..100000] of longint;
    s:longint;
 
begin
 assign (f,'bfs.in'); reset (f);
 assign (g,'bfs.out'); rewrite (g);
 settextbuf(f,bufin);
 settextbuf (g,bufout);
 readln (f,n,m,s);
 setlength(a,n+1,1);
 for i:=1 to m do
 begin
  readln (f,x,y);
  setlength(a[x],length(a[x])+1);
  inc(a[x,0]);
  a[x,a[x,0]]:=y;
 end;
 ps:=0; pi:=1; cd[1]:=s;
 d[s]:=0;
 viz[s]:=1;
 while ps<pi do
 begin
  inc(ps);
  for i:=1 to a[cd[ps],0] do
   if viz[a[cd[ps],i]]=0 then
   begin
    inc(pi);
    cd[pi]:=a[cd[ps],i];
    viz[cd[pi]]:=1;
    d[cd[pi]]:=d[cd[ps]]+1;
   end;
 end;
 for i:=1 to n do
 begin
  if (d[i]=0) and (i<>s) then d[i]:=-1;
  write (g,d[i],' ');
 end;
 close (f); close (g);
end.