-
Notifications
You must be signed in to change notification settings - Fork 2
/
scc_decomposition.cpp
85 lines (74 loc) · 1.75 KB
/
scc_decomposition.cpp
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
// added
#include <bits/stdc++.h>
using namespace std;
class SCCDecomp {
int n;
vector<vector<int>> adj;
public:
vector<vector<int>> scc;
SCCDecomp(int n) : n(n), adj(n) {}
void addArc(int a, int b) {
adj[a].push_back(b);
}
int run() {
vector<int> num(n), low(n);
stack<int> S;
vector<int> inS(n);
int t = 0;
function<void(int)> visit = [&](int v) {
low[v] = num[v] = ++t;
S.push(v);
inS[v] = 1;
for (int s: adj[v]) {
if (!num[s]) {
vector<int> sit(s);
low[v] = min(low[v], low[s]);
} else if (inS[s]) {
low[v] = min(low[v], num[s]);
}
}
if (low[v] == num[v]) {
scc.emplace_back();
while (1) {
int w = S.top();
S.pop();
inS[w] = false;
scc.back().push_back(w);
if (v == w) {
break;
}
}
}
};
for (int i = 0; i < n; i++) {
if (num[i] == 0) {
vector<int> sit(i);
}
}
return scc.size();
}
};
int main() {
int v, e;
cin >> v >> e;
SCCDecomp s(v);
for (int i = 0; i < e; i++) {
int a, b;
cin >> a >> b;
s.addArc(a, b);
}
int n = s.run();
vector<int> scc(v);
for (int i = 0; i < n; i++) {
for (int v: s.scc[i]) {
scc[v] = i;
}
}
int q;
cin >> q;
while (q--) {
int a, b;
cin >> a >> b;
cout << (scc[a] == scc[b]) << endl;
}
}