The Two Routes
思路
超级水题,建立两个图就行,一个是火车的,一个是公交车的,然后跑两遍floyed。
代码
#include<bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 410;
int a[N][N], b[N][N], n, m;
void init() {
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(i != j)
a[i][j] = b[i][j] = INF;
}
int main() {
// freopen("in.txt", "r", stdin);
int x, y;
scanf("%d %d", &n, &m);
init();
for(int i = 0; i < m; i++) {
scanf("%d %d", &x, &y);
a[x][y] = a[y][x] = 1;
}
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(a[i][j] == INF)
b[i][j] = 1;
for(int k = 1; k <= n; k++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(a[i][k] + a[k][j] < a[i][j])
a[i][j] = a[i][k] + a[k][j];
for(int k = 1; k <= n; k++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
if(b[i][k] + b[k][j] < b[i][j])
b[i][j] = b[i][k] + b[k][j];
if(a[1][n] == INF || b[1][n] == INF) puts("-1");
else printf("%d
", max(a[1][n], b[1][n]));
return 0;
}