Dang_Quan_10_Tin

Kosaraju

Jan 11th, 2021 (edited)
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #define NguyenDangQuan the_author
  2. #define my_heart love_you_to_the_moon_and_back
  3.  
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6. using ll = long long;
  7. using ld = long double;
  8. using ull = unsigned long long;
  9.  
  10. const int N = 2e5 + 5;
  11. int n, m;
  12. vector<int> adj[N], nadj[N], s;
  13. int lt[N], l = 0;
  14.  
  15. void Read(){
  16.     cin >> n >> m;
  17.     while(m--){
  18.         int u, v;
  19.         cin >> u >> v;
  20.         adj[u].push_back(v);
  21.         nadj[v].push_back(u);
  22.     }
  23. }
  24.  
  25. void dfs(int v){
  26.     lt[v] = 1;
  27.     for(auto i : adj[v])
  28.         if(!lt[i])
  29.             dfs(i);
  30.     s.push_back(v);
  31. }
  32.  
  33. void dfs_component(int v){
  34.     lt[v] = l;
  35.     cout << v << " ";
  36.     for(auto i : nadj[v])
  37.         if(!lt[i])
  38.             dfs_component(i);
  39. }
  40.  
  41. void Kosaraju(){
  42.     for(int i = 1; i <= n; ++i)
  43.         if(lt[i] == 0)
  44.             dfs(i);
  45.     for(int i = 1; i <= n; ++i)
  46.         lt[i] = 0;
  47.     while(s.size()){
  48.         int c = s.back();
  49.         s.pop_back();
  50.         if(lt[c] != 0)
  51.             continue;
  52.         ++l;
  53.         dfs_component(c);
  54.         cout << "\n";
  55.     }
  56. }
  57.  
  58. void Solve(){
  59.     Kosaraju();
  60.     cout << l;
  61. }
  62.  
  63. main(){
  64.     ios::sync_with_stdio(0);
  65.     cin.tie(0);
  66.     cout.tie(0);
  67.     Read();
  68.     Solve();
  69. }
Add Comment
Please, Sign In to add comment