Created
April 3, 2019 05:41
-
-
Save GoBigorGoHome/b210f5d8ce434ecce9a1ae600688813e to your computer and use it in GitHub Desktop.
任意有向图求传递闭包。Tarjan SCC + bitset 优化。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const int nax = 10005; | |
vector<int> g[nax]; | |
int scc_id[nax]; | |
int dn[nax]; // dfs_no | |
int dfs_clock; | |
int low[nax]; | |
bitset<nax> bs[nax]; | |
vector<bool> in_stack(nax); | |
stack<int> stk; | |
int scc_cnt; | |
void dfs(int u) { | |
dn[u] = low[u] = ++dfs_clock; | |
stk.push(u); in_stack[u] = true; | |
FOR (v, g[u]) { | |
if (!dn[v]) { | |
dfs(v); | |
low[u] = min(low[u], low[v]); | |
} | |
else if (in_stack[v]) { | |
low[u] = min(low[u], dn[v]); | |
} | |
} | |
if (low[u] == dn[u]) { | |
while (true) { | |
int v = stk.top(); stk.pop(); in_stack[v] = false; | |
scc_id[v] = scc_cnt; | |
bs[scc_cnt].set(v); | |
FOR (x, g[v]) { | |
if (scc_id[x] != scc_cnt) { | |
bs[scc_cnt] |= bs[scc_id[x]]; | |
} | |
} | |
if (v == u) break; | |
} | |
++scc_cnt; | |
} | |
} | |
void get_scc(int n) { | |
for (int i = 1; i <= n; ++i) { | |
if (!dn[i]) dfs(i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment