Tram POJ - 1847 最短路变形

一、内容

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

二、思路

  • Switch in the i-th intersection is initially pointing in the direction of the first intersection listed.(这句话代表第i个路口的开关最开始指向的是第一个) 那么说明到达第一个点不用转换,而到达后面的点需要转换开关
  • 故我们建立 u代表第几个路口, 若是直接指向的(即第一个点) 那么边权为0,若是后面必须转换一次的点,那么边权为0。 最后求a到b的最短路即可。

三、代码

#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std; 
const int N = 105, INF = 0x3f3f3f3f;
int n, a, b, g[N][N], k, v; 
void floyd() { 
	for (int k = 1; k <= n; k++) {
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
      			g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
			}
		}	
	}
}
int main() {
	memset(g, 0x3f, sizeof(g));
	scanf("%d%d%d", &n, &a, &b);
	for (int u = 1; u <= n; u++) {
		scanf("%d", &k);
		for (int j = 1; j <= k; j++) {
			scanf("%d", &v);
			if (j == 1) g[u][v] = 0; //开关最开始指向的是第一个 所以权值为0
			else g[u][v] = 1;
		}
	}	
	floyd();
	if (g[a][b] == INF) printf("-1");
	else printf("%d", g[a][b]);
	return 0;
}
发布了343 篇原创文章 · 获赞 244 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41280600/article/details/103922599