diff --git a/graph/articulations_bridges.cpp b/graph/articulations_bridges.cpp index a88d707e7f5df0d04c8d9e242a08813790a55ddd..e2dc35054b207947bc70d2c1b83e032695e2521a 100644 --- a/graph/articulations_bridges.cpp +++ b/graph/articulations_bridges.cpp @@ -36,3 +36,8 @@ void dfs(int x) { } } } + +void tarjan(int v) { + memset(parent, -1, sizeof parent); + dfs(v); +} diff --git a/graph/kosaraju.cpp b/graph/kosaraju.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6808abde3d9bcb23e8be79afe6861438237a82e5 --- /dev/null +++ b/graph/kosaraju.cpp @@ -0,0 +1,62 @@ +/** + * Kosaraju + * + * Complexity (Time): O(n + m) + * Complexity (Space): O(n + m) + */ + +stack<int> S; +vector<int> graph[MAX]; +vector<int> transp[MAX]; + +bool cont[MAX]; + +// Traverse a SCC +void dfs(int x) { + // x belong to current scc + cont[x] = true; + + for (auto i : transp[x]) + if (!cont[i]) + dfs(i); +} + +// Fill stack with DFS starting points to find SCC +void fill_stack(int x) { + cont[x] = true; + + for (auto i : graph[x]) + if (!cont[i]) + fill_stack(i); + + S.push(x); +} + +// Return number of SCC of a graph with n vertices +int kosaraju(int n) { + int scc = 0; + + memset(cont, 0, sizeof cont); + for (int i = 0; i < n; ++i) + if (!cont[i]) + fill_stack(i); + + // Transpose graph + for (int i = 0; i < n; ++i) + for (auto j : graph[i]) + transp[j].push_back(i); + + // Count SCC + memset(cont, 0, sizeof cont); + while (!S.empty()) { + int v = S.top(); + S.pop(); + + if (!cont[v]) { + dfs(v); + scc++; + } + } + + return scc; +}