SSL JudgeOnline 1194——最佳乘车

Description

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

Input

  输入的第一行有两个数字M和N(1<=M<=100 1

Output

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

Sample Input

3 7
6 7
4 7 3 6
2 1 3 5
Sample Output


这题是一道bfs的题

我们将每一条路线都都设为Ture,然后我们每次从一搜到n。假如这条路线是存在的(就是为Ture),而且没有被走过(因为已经走过的肯定是最优的)。然后直到搜到最短路线或者找不到最短路就退出。

如找到最短路径就输出,没有则输出NO


代码如下:

var a:array[1..500,1..500]of boolean;
    state,father,r:array[1..500]of longint;
    f:array[1..500]of boolean;
    n,m,k,i,j:longint;

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

begin
  fillchar(a,sizeof(a),false);
  fillchar(state,sizeof(state),#0);
  readln(m,n);
  for i:=1 to m do
    begin
      k:=0;
      repeat
        inc(k);
        read(r[k]);
        for j:=1 to k-1 do a[r[j],r[k]]:=true;
      until eoln;
    end;
  bfs;
end.
原文地址:https://www.cnblogs.com/Comfortable/p/8412453.html