LuoGuP2296寻找道路

LuoGuP2296寻找道路

简化题意 \(:\)

要求从 \(1\) 号点到 \(n\) 号点的最短路,不能走障碍点.

一个点不是障碍当且仅当它的所有出边指向的点能到达终点.

如何去判断一个点是否是障碍点呢 \(?\)

很简单,我们先做一遍逆拓扑(也就是在反图上以终点为起点做 \(bfs\)),处理出哪些点能与终点连通.

枚举每个点,遍历其所有出边指向的点,如果存在一个点与终点不连通,就把当前点标记为障碍.

最后再正向做一遍 \(bfs\) 即可.

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <ctime>
#include <map>
#include <set>
#define MEM(x,y) memset ( x , y , sizeof ( x ) )
#define rep(i,a,b) for (int i = (a) ; i <= (b) ; ++ i)
#define per(i,a,b) for (int i = (a) ; i >= (b) ; -- i)
#define pii pair < int , int >
#define one first
#define two second
#define rint read<int>
#define int long long
#define pb push_back
#define db double
#define ull unsigned long long
#define lowbit(x) ( x & ( - x ) )

using std::queue ;
using std::set ;
using std::pair ;
using std::max ;
using std::min ;
using std::priority_queue ;
using std::vector ;
using std::swap ;
using std::sort ;
using std::unique ;
using std::greater ;

template < class T >
    inline T read () {
        T 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 << 3 ) + ( x << 1 ) + ( ch - 48 ) ;
            ch = getchar () ;
       }
       return f * x ;
    }

const int N = 1e4 + 100 ;
vector < int > G[N] , E[N] ;
int n , m , s , t , dis[N] ;
bool vis[N] , reach[N] ;

queue < int > q ;
inline void bfs (int cur) {
    q.push ( cur ) ; vis[cur] = true ;
    while ( ! q.empty () ) {
        int j = q.front () ; q.pop () ;
        for (int k : E[j]) {
            if ( vis[k] ) continue ;
            vis[k] = true ; q.push ( k ) ;
        }
    }
    return ;
}

inline void BFS (int cur) {
    while ( ! q.empty () ) q.pop () ;
    rep ( i , 1 , n ) dis[i] = - 1 ;
    dis[cur] = 0 ; q.push ( cur ) ;
    while ( ! q.empty () ) {
        int j = q.front () ; q.pop () ;
        for (int k : G[j]) {
            if ( dis[k] != - 1 || ! reach[k] ) continue ;
            dis[k] = dis[j] + 1 ; q.push ( k ) ;
        }
    }
    return ;
}

signed main (int argc , char * argv[]) {
    n = rint () ; m = rint () ;
    rep ( i , 1 , m ) {
        int u = rint () , v = rint () ;
        E[v].pb ( u ) ; G[u].pb ( v ) ;
    }
    s = rint () ; t = rint () ; bfs ( t ) ;
    rep ( i , 1 , n ) reach[i] = true ;
    rep ( i , 1 , n ) for (int k : G[i]) if ( ! vis[k] )
        { reach[i] = false ; break ; }
    BFS ( s ) ; printf ("%lld\n" , dis[t] ) ;
    #ifndef ONLINE_JUDGE
    system ("pause") ;
    #endif
    return 0 ;
}
posted @ 2019-10-29 08:52  Phecda  阅读(98)  评论(0编辑  收藏  举报

Contact with me