题目描述
H 城是一个旅游胜地,每年都有成千上万的人前来观光。
为方便游客,巴士公司在各个旅游景点及宾馆,饭店等地都设置了巴士站并开通了一些单程巴士线路。
每条单程巴士线路从某个巴士站出发,依次途经若干个巴士站,最终到达终点巴士站。
一名旅客最近到 H 城旅游,他很想去 S 公园游玩,但如果从他所在的饭店没有一路巴士可以直接到达 S 公园,则他可能要先乘某一路巴士坐几站,再下来换乘同一站台的另一路巴士,这样换乘几次后到达 S 公园。
现在用整数 1,2,…N 给 H 城的所有的巴士站编号,约定这名旅客所在饭店的巴士站编号为 1,S 公园巴士站的编号为 N。
写一个程序,帮助这名旅客寻找一个最优乘车方案,使他在从饭店乘车到 S 公园的过程中换乘的次数最少。
思路
对每一趟巴士从当前站点到后续所有可达站建立边权为 1 的有向边,用邻接矩阵存储,这样从 1 号点到 n 号点的最短路 - 1 即为换乘次数,若 n 为 1 则不需要乘车输出0即可(注意因为站点数目未知,可使用sstream流读入)
//#pragma GCC optimize(2)
//#pragma GCC optimize(3)
//#pragma GCC optimize("Ofast", "inline", "-ffast-math")
//#pragma GCC target("abm,avx,mmx,popcnt,sse,sse2,sse3,ssse3,sse4")
#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
#include <sstream>
#include <vector>
#define dbg(x) cout << #x << '=' << x << endl
#define dbg1(x, y) cout << #x << '=' << x << ',' << #y << '=' << y << endl
#define FA ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define INF 0x3f3f3f3f
using namespace std;
const int N = 5e2 + 10, M = 2 * N, mod = 1e9 + 7;
const double eps = 1e-8;
typedef long long LL;
typedef pair<int, int> PII;
int n, m;
int g[N][N];
int dist[N];
bool st[N];
void bfs() {
memset(dist, 0x3f, sizeof dist);
queue<int> q;
q.push(1);
dist[1] = 0;
st[1] = 1;
while (q.size()) {
int t = q.front();
q.pop();
for (int i = 1; i <= n; i++) {
if (g[t][i] && !st[i]) {
st[i] = 1;
q.push(i);
dist[i] = min(dist[i], dist[t] + 1);
}
}
}
}
void solve() {
cin >> m >> n;
vector<int> stop(n, 0);
getchar();
string line;
while (m--) {
getline(cin, line);
stringstream ss(line);
int cnt = 0, p;
while (ss) {
ss >> p;
stop[cnt++] = p;
}
for (int i = 0; i < cnt; i++) {
for (int j = i + 1; j < cnt; j++) {
g[stop[i]][stop[j]] = 1;
}
}
}
bfs();
if (dist[n] == INF)
puts("NO");
else
cout << max(dist[n] - 1, 0) << endl;
}
signed main() {
int T = 1;
while (T--) solve();
}