题解 | #寻找道路#

寻找道路

https://ac.nowcoder.com/acm/problem/16498

alt

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

const int N = 10010, M = 2e5 + 10;

int n, m, s, t;
int h1[N], e1[M], ne1[M], idx1;
int h2[N], e2[M], ne2[M], idx2;
bool st[N];
int d[N];

void add(int a, int b)
{
    e1[idx1] = b, ne1[idx1] = h1[a], h1[a] = idx1 ++;
    e2[idx2] = a, ne2[idx2] = h2[b], h2[b] = idx2 ++;
}

bool check(int u)
{
    for (int i = h1[u]; ~i; i = ne1[i])
        if (!st[e1[i]])
            return false;
    return true;
}

void bfs(int u, int type)
{
    queue<int> q;
    if (!type)
    {
        q.push(u);
        st[u] = true;
        while (!q.empty())
        {
            int t = q.front(); q.pop();
            for (int i = h2[t]; ~i; i = ne2[i])
            {
                int j = e2[i];
                if (!st[j]) q.push(j), st[j] = true;
            }
        }
        return ;
    }
    
    q.push(u);
    while (!q.empty())
    {
        int k = q.front(); q.pop();
        if (!check(k)) continue;
        for (int i = h1[k]; ~i; i = ne1[i])
        {
            int j = e1[i];
            if (!d[j]) 
            {
                d[j] = d[k] + 1;
                if (j == t) {cout << d[t] << endl; return ;}
                q.push(j);
            }
        }
    }
}

int main()
{
    cin >> n >> m;
    memset(h1, -1, sizeof h1), memset(h2, -1, sizeof h2);
    while (m --)
    {
        int a, b; cin >> a >> b;
        add(a, b);
    }
    cin >> s >> t;
    
    bfs(t, 0);
    bfs(s, 1);
    
    return 0;
}
全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-08 00:50
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务