Advertisement
RaFiN_

strongly connected compo by _Ash__

Jul 7th, 2020
1,010
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. // 1-based
  2. /*
  3. scc[i] = nodes in i th component
  4. who[i] = which component node i belongs
  5. sccg[i] = scc graph
  6. comp = how many components
  7. */
  8. namespace SCC {
  9.     vector<vector<int>> g, rg, scc, sccg;
  10.     vector<int> nodes, vis, who;
  11.     int comp, n;
  12.     void init(int n_) {
  13.         n = n_;
  14.         g.assign(n+1,{});
  15.         rg.assign(n+1,{});
  16.         vis.assign(n+1,0);
  17.         nodes.clear();
  18.         who.assign(n+1,0);
  19.         comp = 0;
  20.     }
  21.     void addEdge(int u, int v) {
  22.         g[u].push_back(v);
  23.         rg[v].push_back(u);
  24.     }
  25.     void dfs1(int u) {
  26.         vis[u] = 1;
  27.         for(int v : g[u]) {
  28.             if(!vis[v]) dfs1(v);
  29.         }
  30.         nodes.push_back(u);
  31.     }
  32.     void dfs2(int u) {
  33.         who[u] = comp;
  34.         for(int v: rg[u]) {
  35.             if (!who[v]) dfs2(v);
  36.         }
  37.     }
  38.     void SCC() {
  39.         for(int i = 1; i <= n; i++) {
  40.             if(!vis[i]) dfs1(i);
  41.         }
  42.         reverse(nodes.begin(), nodes.end());
  43.         for(int u: nodes) {
  44.             if (!who[u]) {
  45.                 ++comp;
  46.                 dfs2(u);
  47.             }
  48.         }
  49.         scc.assign(comp+1,{});
  50.         for(int i = 1; i <= n; i++) {
  51.             scc[who[i]].push_back(i);
  52.         }
  53.         sccg.assign(comp + 1,{});
  54.         for(int u = 1; u <= n; u++) {
  55.             for(int v : g[u]) {
  56.                 if (who[u] != who[v]) {
  57.                     sccg[who[u]].push_back(who[v]);
  58.                 }
  59.             }
  60.         }
  61.         for(int i = 1; i <= comp; i++) {
  62.             sort(sccg[i].begin(), sccg[i].end());
  63.             sccg[i].erase(unique(sccg[i].begin(), sccg[i].end()), sccg[i].end());
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement