Advertisement
Araf_12

strongly_connected_components

Apr 1st, 2025
578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 1e5 + 1;
  5.  
  6. vector<int> adj[N], adj_t[N]; // adj_t is the transpose of adj
  7. vector<int> order;            // stores nodes in order of finishing times
  8. vector<bool> vis(N);          // visited array
  9. vector<int> id(N);            // component id for each node
  10. int component_count = 0;      // counts number of SCCs
  11.  
  12. // First DFS pass to fill the order vector
  13. void dfs1(int v) {
  14.     vis[v] = true;
  15.     for (int u : adj[v]) {
  16.         if (!vis[u]) {
  17.             dfs1(u);
  18.         }
  19.     }
  20.     order.push_back(v);
  21. }
  22.  
  23. // Second DFS pass on the transpose graph
  24. void dfs2(int v, int comp) {
  25.     vis[v] = true;
  26.     id[v] = comp;
  27.     for (int u : adj_t[v]) {
  28.         if (!vis[u]) {
  29.             dfs2(u, comp);
  30.         }
  31.     }
  32. }
  33.  
  34. int main() {
  35.     int n, m; // n = number of nodes, m = number of edges
  36.     cin >> n >> m;
  37.  
  38.     // Read edges and build both original and transpose graphs
  39.     for (int i = 0; i < m; i++) {
  40.         int u, v;
  41.         cin >> u >> v;
  42.         adj[u].push_back(v);
  43.         adj_t[v].push_back(u);
  44.     }
  45.  
  46.     // First DFS pass to get processing order
  47.     fill(vis.begin(), vis.end(), false);
  48.     for (int i = 1; i <= n; i++) {
  49.         if (!vis[i]) {
  50.             dfs1(i);
  51.         }
  52.     }
  53.  
  54.     // Second DFS pass on transpose graph in reverse order
  55.     fill(vis.begin(), vis.end(), false);
  56.     reverse(order.begin(), order.end());
  57.     for (int v : order) {
  58.         if (!vis[v]) {
  59.             dfs2(v, component_count++);
  60.         }
  61.     }
  62.  
  63.     // Output results
  64.     cout << "Number of strongly connected components: " << component_count << endl;
  65.     cout << "Component assignments:\n";
  66.     for (int i = 1; i <= n; i++) {
  67.         cout << "Node " << i << " is in component " << id[i] << endl;
  68.     }
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement