洛谷P2296 寻找道路 BFS 审题

开始没好好看题,竟然重写了两遍……
思路很好想,从终点开始倒着BFS,记录可到达的节点。再枚举从1到n中不可到的节点并将该与节点有直接连边的节点打上delete标记.
最后再从终点倒着来一遍BFS即可.
Code:


#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 200000 + 3;
int head[maxn<<1], to[maxn<<1], nex[maxn<<1], cnt;
int mark[maxn], du[maxn], vis[maxn],d[maxn],del[maxn];
queue<int>Q;
inline void add_edge(int u,int v)
{
    nex[++cnt] = head[u], head[u] = cnt, to[cnt] = v;
}
inline void solve(int s)
{
    Q.push(s);
    mark[s] = 1;
    while(!Q.empty())
    {
        int u = Q.front();Q.pop();
        for(int v = head[u]; v ; v = nex[v])
            if(!mark[to[v]])
            {
                mark[to[v]] = 1;
                Q.push(to[v]);
            }
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i = 1;i <= m;++i)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        add_edge(b,a);
        du[a] = 1;
    }
    int s,t;
    scanf("%d%d",&s,&t);
    solve(t);
    for(int i = 1;i <= n;++i)
    {
        if(!mark[i])
        {
            del[i] = 1;
            for(int v = head[i]; v ; v = nex[v])
            {
                del[to[v]] = 1;
            }
        }
    }
    Q.push(t);
    vis[t] = 1, d[s] = -1;
    while(!Q.empty())
    {
        int u = Q.front();Q.pop();
        for(int v = head[u]; v ; v = nex[v])
            if(!vis[to[v]] && !del[to[v]])
            {
                vis[to[v]] = 1, d[to[v]] = d[u] + 1;
                Q.push(to[v]);
            }
        if(vis[s]) break;
    }
    printf("%d",d[s]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liyong1009s/article/details/82227482