https://blog.csdn.net/qq_45228537/article/details/103671868
题目链接:
1008 Airline Routes (35分)
思路:
将有向图分为若干强连通分量的裸题
使用正反dfs的Kosaraju算法或者效率高一些、一次dfs的Tarjan算法即可;
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 12345;
int dfn, scc_cnt, num[maxn], low[maxn], sccno[maxn];
vector<int> G[maxn];
stack<int> stk;
void dfs(int u){
stk.push(u);
num[u] = low[u] = ++dfn;
for(int& v : G[u]){
if(!num[v]) dfs(v), low[u] = min(low[u], low[v]);
else if(!sccno[v]) low[u] = min(low[u], num[v]);
}
if(low[u] == num[u]){
++scc_cnt;
for(;;){
int v = stk.top(); stk.pop();
sccno[v] = scc_cnt;
if(u == v) break;
}
}
}
int main(){
#ifdef MyTest
freopen("Sakura.txt", "r", stdin);
#endif
int n, m, k;
scanf("%d %d", &n, &m);
while(m--){
int x, y; scanf("%d %d", &x, &y);
G[x].push_back(y);
}
for(int i = 1; i <= n; i++) if(!num[i]) dfs(i);
scanf("%d", &k);
while(k--){
int x, y; scanf("%d %d", &x, &y);
if(sccno[x] == sccno[y]) puts("Yes");
else puts("No");
}
return 0;
}