Advertisement
Matrix_code

graph - Strongly Connected Components

Feb 13th, 2021
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. /*
  2.  * Tarjan's Algorithm to find SCC of a directed Graph
  3.  * Complexity: O(V+E)
  4.  *
  5.  * Usage:
  6.  * - init(n) : n is #nodes, 0 indexed
  7.  * - add(u,v): Adds a directed edge from u to v
  8.  * - doscc() : Processes the graph and finds out SCC of the graph
  9.  */
  10.  
  11. struct scc {
  12.   vector<vector<int>> g;
  13.   vector<int> scc, low, ind;
  14.   int n, T, col;
  15.   void init(int _n) {
  16.     n = _n, T = 0, col = 0;
  17.     g.clear();
  18.     g.resize(n);
  19.     scc.assign(n, -1);
  20.     low.assign(n, -1);
  21.     ind.assign(n, -1);
  22.   }
  23.  
  24.   void add(int u, int v) { g[u].push_back(v); }
  25.  
  26.   vector<int> stk;
  27.   void dfs(int u) {
  28.     low[u] = ind[u] = ++T;
  29.     stk.push_back(u);
  30.  
  31.     for (auto v : g[u]) {
  32.       if (ind[v] == -1)
  33.         dfs(v);
  34.       if (scc[v] == -1)
  35.         low[u] = min(low[u], low[v]);
  36.     }
  37.  
  38.     if (ind[u] == low[u]) {
  39.       int t;
  40.       do {
  41.         t = stk.back();
  42.         stk.pop_back();
  43.         scc[t] = col;
  44.       } while (t != u);
  45.       col++;
  46.     }
  47.   }
  48.   void doscc() {
  49.     for (int i = 0; i < n; i++)
  50.       if (ind[i] == -1)
  51.         dfs(i);
  52.   }
  53. };
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement