【洛谷习题】电车
题目链接:https://www.luogu.org/problemnew/show/P1346
题目不难,如果将切换开关次数看做边权,跑一遍最短路就是答案。因为数据范围很小,所以用最容易写的Floyd就可以。只不过初始化时需要注意,先将最短路全部设为inf,如果从一个点到另一个点之间有路径,那么最短路应为1或0(若边的终点恰好是起点的第一个连向的点,则为0)。
1 #include <cstdio> 2 #include <cstring> 3 4 const int maxn = 105, inf = 0x3f3f3f3f; 5 6 int dist[maxn][maxn]; 7 8 int main() { 9 int n, a, b; 10 scanf("%d%d%d", &n, &a, &b); 11 memset(dist, inf, sizeof(dist)); 12 for (int i = 1; i <= n; ++i) { 13 int k, t; 14 scanf("%d", &k); 15 for (int j = 1; j <= k; ++j) { 16 scanf("%d", &t); 17 if (j == 1) dist[i][t] = 0; 18 else dist[i][t] = 1; 19 } 20 } 21 for (int k = 1; k <= n; ++k) 22 for (int i = 1; i <= n; ++i) 23 for (int j = 1; j <= n; ++j) 24 if (dist[i][j] > dist[i][k] + dist[k][j]) 25 dist[i][j] = dist[i][k] + dist[k][j]; 26 if (dist[a][b] == inf) printf("-1"); 27 else printf("%d", dist[a][b]); 28 return 0; 29 }