Tram network in Zagreb consists of a number of intersections and rails connecting some of them. In every intersection there is a switch pointing to the one of the rails going out of the intersection. When the tram enters the intersection it can leave only in the direction the switch is pointing. If the driver wants to go some other way, he/she has to manually change the switch.
When a driver has do drive from intersection A to the intersection B he/she tries to choose the route that will minimize the number of times he/she will have to change the switches manually.
Write a program that will calculate the minimal number of switch changes necessary to travel from intersection A to intersection B.
Input
The first line of the input contains integers N, A and B, separated by a single blank character, 2 <= N <= 100, 1 <= A, B <= N, N is the number of intersections in the network, and intersections are numbered from 1 to N.
Each of the following N lines contain a sequence of integers separated by a single blank character. First number in the i-th line, Ki (0 <= Ki <= N-1), represents the number of rails going out of the i-th intersection. Next Ki numbers represents the intersections directly connected to the i-th intersection.Switch in the i-th intersection is initially pointing in the direction of the first intersection listed.
Output
The first and only line of the output should contain the target minimal number. If there is no route from A to B the line should contain the integer “-1”.
Sample Input
3 2 1
2 2 3
2 3 1
2 1 2
Sample Output
0
电动巴士在每个十字路口有一个默认方向,走向别的方向需要改动扳手。
第一行给定十字路口的数量和起点终点
剩余n行给定与第i个十字路口相通的方向,第一个为默认方向
注意读题,英语差的我wa到哭啊
#include<stdio.h>
#include<string.h>
#include<vector>
#include<queue>
#define MAX_N 300
#define INF 0x3f3f3f3f
using namespace std;
int d[MAX_N];
int spfa(int n,int s,int e,vector<int> *G){
memset(d,0x3f,sizeof(d));
queue<int> que;
d[s]=0;
que.push(s);
while(!que.empty()){
int t=que.front();que.pop();
if(G[t].empty()) continue;
if(d[G[t][0]]>d[t]){
d[G[t][0]]=d[t];
que.push(G[t][0]);
}
for(int i=1;i<G[t].size();i++){
if(d[G[t][i]]>d[t]+1){
d[G[t][i]]=d[t]+1;
que.push(G[t][i]);
}
}
}
return d[e]!=INF?d[e]:-1;
}
int main(){
int n,s,e;
while(scanf("%d%d%d",&n,&s,&e)!=EOF){
vector<int> G[n+1];
for(int i=1;i<=n;i++){
int cum;
scanf("%d",&cum);
for(int j=0;j<cum;j++){
int get;
scanf("%d",&get);
G[i].push_back(get);
}
}
printf("%d\n",spfa(n,s,e,G));
}
return 0;
}