题意抽象:每条公交线路是单向的。从起点出发,到终点,最少需要换成多少次。
思路:如果目的是换乘次数最少。那么其实在一条公交路线上,从起点到任何一个点的权重都是一样的。然后建图其实是最复杂的。前边的点,都需要指向后边的点,权重都还是一样。
最终的换乘次数就是起点到终点的距离-1. 如果不需要换乘,那么结果就是0。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<sstream>
using namespace std;
const int N = 510;
int m, n;
// 由于不用存权重,所以直接用bool数组就可以
bool g[N][N];
int dist[N];
int stop[N]; // 存经过的车站
int q[N];
// 边权都一样,所以bfs也可以求最短距离。
void bfs()
{
int hh = 0, tt = 0;
memset(dist, 0x3f, sizeof dist);
q[0] = 1; //起点入队
dist[1] = 0;
while(hh <= tt)
{
// 队列头出队
int t = q[hh++];
// 遍历和t相连的边,更新
for(int i=1; i<=n; i++)
if(g[t][i] && dist[i]>dist[t] + 1)
{
dist[i] = dist[t] + 1;
q[++tt] = i;
}
}
}
int main()
{
cin >> m >> n;
// 一行不知道有多少个,难处理
string line;
getline(cin, line);
while(m--)
{
getline(cin, line);
stringstream ssin(line);
int cnt = 0, p;
while(ssin >> p) stop[cnt++] = p;
for(int j=0; j<cnt; j++)
for(int k = j+1; k<cnt; k++)
g[stop[j]][stop[k]] = true;
}
bfs();
if(dist[n] == 0x3f3f3f3f) puts("NO");
// 如果dist[N] = 0, 不用换乘,不能输出-1,
// 要和0取一个max
else cout<<max(dist[n] -1, 0) << endl;
return 0;
}