codevs 1571 电车

屠龙宝刀点击就送

题目描述 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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值