Tram
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 11159 | Accepted: 4089 |
Description
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
Source
Croatia OI 2002 Regional - Juniors
题解:带权值的最短路,floyd算法
代码:
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 #define N 1000000 5 int map[101][101]; 6 int main() 7 { 8 int n,sta,end,m,a; 9 int i,j; 10 11 scanf("%d%d%d",&n,&sta,&end); 12 for(i=1; i<=n; i++) 13 for(j=1; j<=n; j++) 14 map[i][j]=N; 15 for(i=1; i<=n; i++) 16 { 17 scanf("%d",&m); 18 for(j=1; j<=m; j++) 19 { 20 scanf("%d",&a); 21 if(j==1) 22 map[i][a]=0; 23 else 24 map[i][a]=1; 25 } 26 } 27 28 int k; 29 for(k=1; k<=n; k++) //floyd算法 30 for(i=1; i<=n; i++) 31 for(j=1; j<=n; j++) 32 if(map[i][k]+map[k][j]<map[i][j]) 33 map[i][j]=map[i][k]+map[k][j]; 34 35 if(map[sta][end]<N) 36 cout<<map[sta][end]<<endl; 37 else 38 cout<<-1<<endl; 39 return 0; 40 }