Fork me on GitHub

LuoGuP2296寻找道路

LuoGuP2296寻找道路

简化题意 $:$

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

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

如何去判断一个点是否是障碍点呢 $?$

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

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

最后再正向做一遍 $bfs$ 即可.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#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 ;
}