zoukankan      html  css  js  c++  java
  • 洛谷P2296 寻找道路_简单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;
    }
    
  • 相关阅读:
    活着就是幸福
    ibatis配置log4j输出sql语句等日志信息
    每天记录点点滴滴
    SSH整合 创建SessionFactory
    活着
    最经典的智力题
    struts整合spring整合hibernate
    让MyEclipse里的Tomcat自动reloadable
    明天就会有阳光...
    数据表字段为空时的判断
  • 原文地址:https://www.cnblogs.com/guangheli/p/9845138.html
Copyright © 2011-2022 走看看