用tarjan把所有的环都指向各自环中的最先访问的节点
题目询问即问两个点是否在同一个环中
#pragma warning(disable:4996)
#include<iostream>
#include<vector>
#define min(x,y) (x<y? x:y)
using namespace std;
const int maxn = 10005;
int Vt[maxn], R[maxn], t, N, M, a, b, K, sta[maxn], top = -1, vis[maxn];
vector<int> G[maxn];
void dfs(int index) {
for (auto x : G[index]) {
if (!Vt[x])
R[x] = Vt[x] = ++t, sta[++top] = x, vis[x] = 1, dfs(x), R[index] = min(R[index], R[x]);
else if (vis[x])
R[index] = min(R[index], Vt[x]);
}
if (Vt[index] == R[index])
do{
R[sta[top]] = Vt[index], vis[sta[top]] = 0;
} while (sta[top--] != index);
}
int main() {
#ifdef _DEBUG
freopen("in", "r", stdin);
#endif // _DEBUG
scanf("%d %d", &N, &M);
while (M--)
scanf("%d %d", &a, &b), G[a].push_back(b);
for (int i = 1; i <= N; ++i)
if (!Vt[i]) R[i] = Vt[i] = ++t, sta[++top] = i, vis[i] = 1, dfs(i);
scanf("%d", &K);
while (K--)
scanf("%d %d", &a, &b), printf(R[a] == R[b] ? "Yes\n" : "No\n");
}