codevs 1571 电车

来源:互联网 发布:阿拉伯血钻野燕麦知乎 编辑:程序博客网 时间:2024/05/17 04:35

屠龙宝刀点击就送

题目描述 Description
在一个神奇的小镇上有着一个特别的电车网络,它由一些路口和轨道组成,每个路口都连接着若干个轨道,每个轨道都通向一个路口(不排除有的观光轨道转一圈后返回路口的可能)。在每个路口,都有一个开关决定着出去的轨道,每个开关都有一个默认的状态,每辆电车行驶到路口之后,只能从开关所指向的轨道出去,如果电车司机想走另一个轨道,他就必须下车切换开关的状态。
为了行驶向目标地点,电车司机不得不经常下车来切换开关,于是,他们想请你写一个程序,计算一辆从路口A到路口B最少需要下车切换几次开关。

输入描述 Input Description
第一行有3个整数2<=N<=100,1<=A,B<=N,分别表示路口的数量,和电车的起点,终点。
接下来有N行,每行的开头有一个数字Ki(0<=Ki<=N-1),表示这个路口与Ki条轨道相连,接下来有Ki个数字表示每条轨道所通向的路口,开关默认指向第一个数字表示的轨道。

输出描述 Output Description
输出文件只有一个数字,表示从A到B所需的最少的切换开关次数,若无法从A前往B,输出-1。

样例输入 Sample Input
3 2 1

2 2 3

2 3 1

2 1 2

样例输出 Sample Output
0

SPFA ↓

#include<iostream>#include<cstdio>#include<cstring>#include<queue>using namespace std;const int MAXN = 5000;struct Edge{    int from, to, cost;}es[MAXN << 2];int first[MAXN << 4], nex[MAXN << 4], d[MAXN << 2];int n, a, b, tot = 1;bool used[MAXN << 2];queue < int > q;void build(int f, int t, int d){    es[++tot].from = f;    es[tot].to = t;    es[tot].cost = d;    nex[tot] = first[f];    first[f] = tot; }void spfa(int s){    d[s] = 0;    q.push(s);    used[s] = 1;    while(!q.empty())    {        int x = q.front();        q.pop();        used[x] = 0;            for(int i = first[x]; i != -1; i = nex[i])        {            int u = es[i].to;            if(d[u] > d[x] + es[i].cost)            {                d[u] = d[x] + es[i].cost;                if(!used[u])                {                    q.push(u);                    used[u] = 1;                }            }        }      }}int main(){    scanf("%d%d%d", &n, &a, &b);    memset(first, -1, sizeof(first));    for(int i = 1; i <= n; i++)    {        int ki, kg;        scanf("%d", &ki);        for(int j = 1; j <= ki; j++)        {            scanf("%d", &kg);            if(j == 1)                build(i, kg, 0);            else                build(i, kg, 1);        }    }    memset(d, 0x3f, sizeof(d));    spfa(a);    if(d[b] >= 0x3f)    {        cout<<"-1";        return 0;    }    printf("%d", d[b]);    return 0;}
2 0