diff --git a/strongly_connected_component.cpp b/strongly_connected_component.cpp new file mode 100644 index 0000000..1829d67 --- /dev/null +++ b/strongly_connected_component.cpp @@ -0,0 +1,64 @@ +#include +using namespace std; + +void dfs(vector>&adj, vector&vis, int node, vector&st) +{ + vis[node] = true; + for (auto nbr : adj[node]) + { + if (!vis[nbr]) + dfs(adj, vis, nbr, st); + } + st.push_back(node); +} + +void dfs_(vector>&adj, vector&vis, int node) +{ + vis[node] = true; + cout << node << " "; + for (auto nbr : adj[node]) + { + if (!vis[nbr]) + dfs_(adj, vis, nbr); + } +} + +int main() +{ + int n, m; + cin >> n >> m; + + vector> adj(n), rev_adj(n); + while (m--) + { + int a, b; + cin >> a >> b; + adj[a].push_back(b); + rev_adj[b].push_back(a); + } + vectorvis(n, false); + vectorst;//use stack + + for (int i = 0; i < n; i++) + { + if (!vis[i]) + dfs(adj, vis, i, st); + } + fill(vis.begin(), vis.end(), false); + + + char comp_name = 'A'; + + for (int i = st.size() - 1; i >= 0; i--) + { + int node = st[i]; + if (!vis[node]) + { + cout << "component " << comp_name << "-->"; + dfs_(rev_adj, vis, node); + cout << endl; + comp_name++; + } + } + +}