Tram(poj1847,floyd)

来源:互联网 发布:阿里xin域名 编辑:程序博客网 时间:2024/05/22 01:44

http://poj.org/problem?id=1847

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=29015#problem/H

H - Tram

Time Limit:1000MS     Memory Limit:30000KB     64bit IO Format:%I64d & %I64u

Submit

 

Status

 

Practice

 

POJ 1847

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

解析:

题意:

已知起点和终点,判断是否存在可行路径,如果则输出最短路径长度

注意,这里与i节点连通的第一个点形成的变得权值为0

思路:

由于数据比较小,因此可以用floyd法求解

212 KB 47 ms C++ 945 B

*/


#include<stdio.h>#include<string.h>#include <iostream>using namespace std;const int maxn=100+10;const int inf=100000001;int d[maxn][maxn];int s,t,n;void floyd(){for(int k=1;k<=n;k++)  for(int i=1;i<=n;i++)   for(int j=1;j<=n;j++)   {   if(d[i][k]<inf&&d[k][j]<inf&&d[i][j]>d[i][k]+d[k][j])    d[i][j]=d[i][k]+d[k][j];   }}int main(){   int i,j;   while(scanf("%d%d%d",&n,&s,&t)!=EOF)   {    for(i=1;i<=n;i++)     for(j=1;j<=n;j++)       {       if(i==j)       d[i][j]=0;       else       d[i][j]=inf;       }       int k,u;       for(i=1;i<=n;i++)       {       scanf("%d",&k);       for(j=1;j<=k;j++)       {        scanf("%d",&u);        if(j==1)        d[i][u]=0;        else        d[i][u]=1;       }       }       floyd();       if(d[s][t]==inf)       {       printf("-1\n");       }       else       printf("%d\n",d[s][t]);   }    return 0;}


原创粉丝点击