Advertisement
arujbansal

Kosaraju's Algorithm for SCCs

Apr 29th, 2021
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <map>
  5. #include <set>
  6. #include <array>
  7. #include <stack>
  8. #include <queue>
  9. #include <random>
  10. #include <numeric>
  11. #include <functional>
  12. #include <chrono>
  13. #include <utility>
  14. #include <iomanip>
  15. #include <assert.h>
  16.  
  17. using namespace std;
  18.  
  19. void dbg_out() { cerr << endl; }
  20. template<typename Head, typename... Tail>
  21. void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
  22. #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
  23.  
  24. #define rng_init mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
  25. #define rng_seed(x) mt19937 rng(x)
  26. #define all(x) (x).begin(), (x).end()
  27. #define sz(x) (int) (x).size()
  28. // #define int long long
  29.  
  30. const int MXN = 5e5 + 5, INF = 1e9 + 5;
  31. vector<int> g[MXN], gr[MXN];
  32. vector<int> topo_order;
  33. int vis[MXN];
  34. vector<vector<int>> components;
  35.  
  36. void dfs1(int u) {
  37.     vis[u] = 1;
  38.  
  39.     for (const auto &v : g[u]) {
  40.         if (vis[v]) continue;
  41.         dfs1(v);
  42.     }
  43.  
  44.     topo_order.push_back(u);
  45. }
  46.  
  47. void dfs2(int u) {
  48.     vis[u] = true;
  49.  
  50.     components.back().push_back(u);
  51.  
  52.     for (const auto &v : gr[u]) {
  53.         if (vis[v]) continue;
  54.         dfs2(v);
  55.     }
  56. }
  57.  
  58. void solve() {
  59.     int N, M;
  60.     cin >> N >> M;
  61.  
  62.     while (M--) {
  63.         int u, v;
  64.         cin >> u >> v;
  65.  
  66.         g[u].push_back(v);
  67.         gr[v].push_back(u);
  68.     }
  69.  
  70.     for (int i = 0; i < N; i++) {
  71.         if (!vis[i]) dfs1(i);
  72.     }
  73.  
  74.     reverse(all(topo_order));
  75.  
  76.     for (int i = 0; i < N; i++)
  77.         vis[i] = false;
  78.  
  79.     for (const auto &node : topo_order) {
  80.         if (vis[node]) continue;
  81.  
  82.         components.emplace_back();
  83.         dfs2(node);
  84.     }
  85.  
  86.     cout << sz(components) << "\n";
  87.  
  88.     for (const auto &component : components) {
  89.         cout << sz(component) << " ";
  90.  
  91.         for (const auto &v : component)
  92.             cout << v << " ";
  93.  
  94.         cout << "\n";
  95.     }
  96. }
  97.  
  98. signed main() {
  99.     ios_base::sync_with_stdio(false);
  100.     cin.tie(nullptr);
  101.  
  102.     int TC = 1;
  103.     // cin >> TC;
  104.     while (TC--) solve();
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement