Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define NguyenDangQuan the_author
- #define my_heart love_you_to_the_moon_and_back
- #include <bits/stdc++.h>
- using namespace std;
- using ll = long long;
- using ld = long double;
- using ull = unsigned long long;
- const int N = 2e5 + 5;
- int n, m;
- vector<int> adj[N], nadj[N], s;
- int lt[N], l = 0;
- void Read(){
- cin >> n >> m;
- while(m--){
- int u, v;
- cin >> u >> v;
- adj[u].push_back(v);
- nadj[v].push_back(u);
- }
- }
- void dfs(int v){
- lt[v] = 1;
- for(auto i : adj[v])
- if(!lt[i])
- dfs(i);
- s.push_back(v);
- }
- void dfs_component(int v){
- lt[v] = l;
- cout << v << " ";
- for(auto i : nadj[v])
- if(!lt[i])
- dfs_component(i);
- }
- void Kosaraju(){
- for(int i = 1; i <= n; ++i)
- if(lt[i] == 0)
- dfs(i);
- for(int i = 1; i <= n; ++i)
- lt[i] = 0;
- while(s.size()){
- int c = s.back();
- s.pop_back();
- if(lt[c] != 0)
- continue;
- ++l;
- dfs_component(c);
- cout << "\n";
- }
- }
- void Solve(){
- Kosaraju();
- cout << l;
- }
- main(){
- ios::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- Read();
- Solve();
- }
Add Comment
Please, Sign In to add comment