思路:
由题意得只有第一个方向不要转距离为 0,其他方向要转距离都为 1,
已知起点和中点,朴素dijkstra即可,感觉最短路的问题很多有建图思路大概就会写了。
样例为答案为 0 的情况解释 :2 -> 3 -> 1
代码:
#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <climits>
#include <iomanip>
#include <queue>
#include <vector>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 110;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;
int a[N][N];
int n, s, t;
bool vis[N];
int dis[N];
int dijkstra()
{
memset(vis, false, sizeof vis);
memset(dis, INF, sizeof dis);
dis[s] = 0;
for (int i = 1; i <= n; i++)
{
int t = -1;
for (int j = 1; j <= n; j++)
{
if (!vis[j] && (t == -1 || dis[j] < dis[t]))
t = j;
}
vis[t] = true;
for (int j = 1; j <= n; j++)
dis[j] = min(dis[j], dis[t] + a[t][j]);
}
if (dis[t] == INF)
return -1;
else
return dis[t];
}
int main()
{
memset(a, INF, sizeof a);
cin >> n >> s >> t;
for (int i = 1; i <= n; i++)
{
int k;
cin >> k;
for (int j = 1; j <= k; j++)
{
int r;
cin >> r;
if (j == 1)
a[i][r] = 0;
else
a[i][r] = 1;
}
}
cout << dijkstra() << endl;
return 0;
}