POJ 1847 Tram

来源:互联网 发布:linux 高性能c日志库 编辑:程序博客网 时间:2024/04/26 12:24

Tram

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 12 2 32 3 12 1 2

Sample Output

0

题意:矿车在轨道上跑需要扳道,给出轨道的有向图求扳道最小次数。输入第一行N A B,轨道交点数和起点终点,下面有N行,每行的行数Ni表示是第Ni个点,每行第一个数表示与Ni相连的有m个点,接下来有m个点。在这m个点中的第一个点m1表示Ni-m1这条轨道的初始方向,不用扳道。

有向图统计边数,第一个边权值为零,其余为一。注意输入只有一组数据。

#include<cstdio>#include<cstring>#include<algorithm>#include<queue>#define N 102using namespace std;int n,sta,en;int map[N][N];int val[N];void letgo(){    int i,f;    for(i=1; i<=N; i++)        val[i]=0xfffffff;    queue<int>q;    f=sta;    val[sta]=0;    q.push(f);    while(!q.empty())    {        f=q.front();        q.pop();        for(i=1; i<=n; i++)        {            if(map[f][i]>=0&&val[f]+map[f][i]<val[i])            {                q.push(i);                val[i]=val[f]+map[f][i];            }        }    }    return ;}int main(){    int i,j,k,m;    memset(val,0,sizeof(val));    scanf("%d%d%d",&n,&sta,&en);    memset(map,-1,sizeof(map));    for(i=1; i<=n; i++)    {        scanf("%d",&m);        for(j=1; j<=m; j++)        {            scanf("%d",&k);            if(j==1)                map[i][k]=0;            else                map[i][k]=1;        }    }    letgo();    if(val[en]==0xfffffff)    {        printf("-1\n");    }    else    printf("%d\n",val[en]);    return 0;}





1 0