Library/Graph/tarjan_scc.cpp

25 lines
789 B
C++
Raw Normal View History

2020-09-06 15:27:17 +00:00
namespace tarjan {
2020-09-06 19:27:14 +00:00
int cnt, scc_num, scc[MX], in[MX], low[MX];
2020-08-21 20:21:02 +00:00
stack<int> s;
2020-09-06 19:27:14 +00:00
bitset<MX> ins;
2020-08-21 20:21:02 +00:00
void tarjan(vector<int> * G, int u) {
low[u] = in[u] = cnt++, ins[u] = 1; s.push(u);
for (int v : G[u]) {
if (in[v] == -1) tarjan(G, v), low[u] = min(low[u], low[v]);
else if (ins[v]) low[u] = min(low[u], in[v]);
}
if (low[u] == in[u]) {
while (1) {
int x = s.top(); s.pop();
scc[x] = scc_num, ins[x] = 0;
if (x == u) break;
}
++scc_num;
}
}
void find_scc(vector<int> * G) {
memset(scc, -1, sizeof scc), memset(in, -1, sizeof in);
for (int u = 1; u <= N; ++u) if (scc[u] == -1) tarjan(G, u);
}
2020-06-13 16:40:33 +00:00
}