Description
H City is a tourist attraction, and thousands of people come to visit each year. To facilitate tourists, bus companies have set up bus stops in various tourist attractions, hotels, and other places, and have opened some one-way bus routes. Each one-way bus line departs from a bus station and passes through several bus stations in turn to finally reach the end bus station. A passenger recently traveled to H city. He really wanted to visit s park. But if he hadn't traveled all the way from his hotel, he could directly reach s Park, then he may have to take a bus several times, and then change to another bus on the same platform, so that he can transfer several times to s Park. Use an integer of 1, 2 ,... N number all bus stops in city H. It is agreed that the bus stop number of the passenger's hotel is 1... S Park Bus Station is numbered n.
Write a program to help the passenger find the best ride plan, so that he will change the car the least number of times from the hotel to s Park.
-
Input
-
There are multiple groups of test data. the first row of each group of data has two numbers, M and N (1 <= m <= 100 1 <n <= 500), indicating that m one-way bus lines are activated, there are n stations in total. From the second row to the m + 1 row, the information of the 1st to the M bus line is provided in sequence. Line I + 1 provides information about the bus line I, all the station numbers on the line are separated by a space from the two adjacent stations in the order of operation from left to right. When M = n = 0 is the end.
-
Output
-
Only one row of output data. If you cannot take a bus from the hotel to s Park, output "N0"; otherwise, output the minimum number of replicas found by your program. If the number of replicas is 0, you do not need to change the number of replicas •
-
Sample Input
-
3 7
6 7
4 7 3 6
2 1 3 5
-
Sample output
-
2
This question is obviously an algorithm in graph theory. Consider using the dijela algorithm.
#include <stdio.h>#define MAX 20000000int a[501][501];int s[501], dist[501];int main(){while(1){int m, n;int i, j, k;int temp,u;scanf("%d %d\n", &m, &n);if(m == 0 && n == 0) break;for(i = 1; i <= n; i ++)for(j = 1; j <= n; j ++)a[i][j] = MAX;for(i = 0; i < m; i ++){k = 0;while(1){char ch;scanf("%d%c", &s[k ++], &ch);for(j = 0; j < k; j ++)a[s[j]][s[k-1]] = 0;if(ch == '\n') break;}}for(i = 1; i <= n; i++) { dist[i] = a[1][i]; s[i] = 0; } dist[1] = 0; s[1] = 1;for(i = 1; i <= n; i ++) { temp = MAX;u = 1; for(j = 1; j <= n;j ++) if(!s[j]&&(dist[j] <temp)) { u = j; temp = dist[j]; }s[u] = 1;for(j = 1; j <= n; j ++) if(!s[j] && (a[u][j] < MAX)) {int newdist = dist[u]+a[u][j]+1;if(newdist < dist[j])dist[j] = newdist;}}if(dist[n] != MAX){printf("%d\n", dist[n]);}else{printf("NO\n");}}return 0;}