diff --git a/graph/tarjan.cpp b/graph/tarjan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f9e1952d18a339abf6c5abe9bdb6fa21c284a162 --- /dev/null +++ b/graph/tarjan.cpp @@ -0,0 +1,53 @@ +/** + * Tarjan - Strongly Connected Components + * + * Complexity (Time): O(n + m) + * Complexity (Space): O(n + m) + */ + +vector<int> graph[MAX]; +vector<int> scc[MAX]; + +stack<int> S; +int ncomp, ind; +int cont[MAX], parent[MAX]; +int low[MAX], L[MAX]; + +// Fills scc with strongly connected components of graph +void dfs(int x) { + L[x] = ind; + low[x] = ind++; + cont[x] = 1; + S.push(x); + + for (auto i : graph[x]) + if (L[i] == -1) { + dfs(i); + low[x] = min(low[x], low[i]); + } else if (cont[i]) + low[x] = min(low[x], L[i]); + + if (low[x] == L[x]) { + int w; + ncomp++; + + do { + w = S.top(); S.pop(); + cont[w] = 0; + scc[ncomp].pb(w); + } while (w != x); + } +} + + +// Return number of SCCs +int tarjan(int n) { + memset(L, -1, sizeof L); + ncomp = ind = 0; + + for (int i = 0; i < n; ++i) + if (L[i] == -1) + dfs(i); + + return ncomp; +}