最优乘车(normal) 1194

来源:互联网 发布:虚拟社交网络的定义 编辑:程序博客网 时间:2024/05/18 00:44

最优乘车(normal)

Time Limit:1000MS  Memory Limit:65536K
Total Submit:258 Accepted:120

Description

  H城是一个旅游胜地,每年都有成千上万的人前来观光。为方便游客,巴士公司在各个旅游景点及宾馆,饭店等地都设置了巴士站并开通了一些单程巴上线路。每条单程巴士线路从某个巴士站出发,依次途经若干个巴士站,最终到达终点巴士站。
  一名旅客最近到H城旅游,他很想去S公园游玩,但如果从他所在的饭店没有一路已士可以直接到达S公园,则他可能要先乘某一路巴士坐几站,再下来换乘同一站台的另一路巴士, 这样换乘几次后到达S公园。
  现在用整数1,2,…N 给H城的所有的巴士站编号,约定这名旅客所在饭店的巴士站编号为1…S公园巴士站的编号为N。
  写一个程序,帮助这名旅客寻找一个最优乘车方案,使他在从饭店乘车到S公园的过程中换车的次数最少。

Input

  输入的第一行有两个数字M和N(1<=M<=100 1<n<=500),表示开通了m条单程巴士线路,总共有n个车站。从第二行到第m刊行依次给出了第1条到第m条巴士线路的信息。其中第i+1行给出的是第i条巴士线路的信息,从左至右按运行顺序依次给出了该线路上的所有站号相邻两个站号之间用一个空格隔开。

Output

  输出文件只有一行。如果无法乘巴士从饭店到达S公园,则输出"N0",否则输出你的程序所找到的最少换车次数,换车次数为0表示不需换车即可到达•

Sample Input

3 76 74 7 3 62 1 3 5

Sample Output

Source

elba


const

  maxn=499;
var
  a:array[1..maxn,1..maxn]of boolean;
  v:array[1..maxn] of boolean;
  state,father:array[1..maxn] of longint;
  m,n,i,j,k:longint;


procedure init;
var
  i,j,k:longint;
  b:array[1..maxn]of longint;
begin
  fillchar(v,sizeof(v),false);
  fillchar(a,sizeof(a),false);
  for i:=1 to maxn do
    state[i]:=-1;
  readln(m,n);
  for i:=1 to m do
    begin
      k:=0;
      repeat
        inc(k);
        read(b[k]);
      for j:=1 to k-1 do
        a[b[j],b[k]]:=true;
      until eoln;
   end;
end;










procedure print(x,head,tail:longint);
begin
  if  head=tail then writeln('NO')
                else writeln(x);
end;


procedure gs;
var
  head,tail,i,j,k:integer;
begin
  head:=0;
  tail:=1;
  father[1]:=1;
  state[1]:=0;
  v[1]:=true;
  repeat
   inc(head);
    for i:=1 to n do
      if (a[father[head],i]=true) and  (v[i]=false) then
            begin
              inc(tail);
              v[i]:=true;
              father[tail]:=i;
              state[i]:=state[father[head]]+1;
            end;
  until (head=tail) or (v[n]=true);
  if v[n]=true then writeln(state[n]-1)
  else writeln('NO');
end;


begin
  init;
  gs;
end.

0 0
原创粉丝点击