洛谷 P2296 寻找道路 题解

版权声明:随便转载。 https://blog.csdn.net/zhang14369/article/details/80800517

一、题目:

洛谷原题

二、思路:

在上一篇中,我讲解了暴力做法,接下来讲正解。
首先,将图取反。
然后从终点开始BFS,标记终点可以到达的点(即原图中可以到达终点的点)。
接着枚举每一个没标记的点x,再枚举x点指向的点y(即原图中到x点的点),如果y点已被标记,说明y点并不合法,删除。
最后SPFA(或BFS)求解。

三、代码:

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

using namespace std;
inline int read(void) {
    int x = 0, f = 1; char ch = getchar();
    while (ch<'0' || ch>'9') {
        if (ch == '-')f = -1;
        ch = getchar();
    }
    while (ch >= '0'&&ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return f * x;
}

const int maxn = 10005, maxm = 200005;

int n, m, head[maxn], tot, start, en, dis[maxn];
bool vis[maxn], vis2[maxn];

struct Edge {
    int y, next;
}e[maxm];

inline void connect(int x, int y) {
    e[++tot].y = y; e[tot].next = head[x]; head[x] = tot; return;
}

inline void init() {
    n = read(); m = read();
    for (register int i = 1; i <= m; i++) {
        int x = read(), y = read();
        if (x == y)continue;
        connect(y, x);
    }
    en = read(); start = read();
    return;
}

inline void solve(void) {
    queue<int>q; q.push(start);
    vis[start] = true;
    while (!q.empty()) {
        int u = q.front(); q.pop();
        for (register int i = head[u]; i; i = e[i].next) {
            int v = e[i].y;
            if (!vis[v]) { q.push(v); vis[v] = true; }
        }
    }
    memcpy(vis2, vis, sizeof(vis));
    for (register int i = 1; i <= n; i++) {
        if (!vis[i]) {
            for (register int j = head[i]; j; j = e[j].next) {
                int v = e[j].y;
                if (vis2[v])vis2[v] = false;
            }
        }
    }
    q.push(start);
    while (!q.empty()) {
        int u = q.front(); q.pop();
        for (register int i = head[u]; i; i = e[i].next) {
            int v = e[i].y;
            if (vis2[v]) {
                q.push(v);
                vis2[v] = false;
                dis[v] = dis[u] + 1;
            }
        }
    }
    if (!dis[en]) { puts("-1"); }
    else printf("%d\n", dis[en]);
}

int main() {
    init();
    solve();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhang14369/article/details/80800517