一個鐵路網絡,每個站點有一個開關,每個站點指向>=0個站點,開關指向的那條路爲通,司機若想走其他路線需要轉換開關。現司機想要從A點走到B點,求最少的開關轉換次數。
本來很簡單的一道題,結果小錯誤一大堆,WA了不少次終於AC了。Floyd直接過。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int inf = 1<<20;
int map[105][105];
int N,A,B;
void init(){
for(int i=0;i<=N;i++){
for(int j=i+1;j<=N;j++){
map[i][j]=map[j][i]=inf;
}
}
}
void floyd(){
for(int k=1;k<=N;k++){
for(int i=1;i<=N;i++){
if(map[i][k]==inf) continue;
for(int j=1;j<=N;j++){
if(i!=j && i!=k && j!=k && map[i][j]>map[i][k]+map[k][j]){
map[i][j]=map[i][k]+map[k][j];
}
}
}
}
}
int main(){
//freopen("in.txt","r",stdin);
cin >> N >> A >> B ;
init();
for(int i=1;i<=N;i++){
int m; cin >> m;
for(int j=1;j<=m;j++){
int t; cin >> t;
if(j==1) {map[i][t]=0;}
else map[i][t]=1;
}
}
floyd();
if(map[A][B]!=inf) cout<<map[A][B]<<endl;
else cout<<-1<<endl;
return 0;
}