Advertisement
Josif_tepe

Untitled

Sep 23rd, 2022
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <vector>
  2. #include <stack>
  3. #include <algorithm>
  4. #include <iostream>
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. vector<int>graph[100005];
  8. vector<int>rev_graph[100005];
  9. bool visited[100005];
  10. int n, m;
  11. int niza[100005];
  12. int idx;
  13. stack<int>s;
  14. void dfs(int node){
  15.     visited[node]=true;
  16. for(int i=0; i<graph[node].size(); i++){
  17.     int sosed=graph[node][i];
  18.     if (!visited[sosed]){
  19.         dfs(sosed);
  20.     }
  21. }
  22. s.push(node);
  23. }
  24. void rev_dfs(int node){
  25.     visited[node]=true;
  26.     niza[node]=idx;
  27. //    cout << node << " " ;
  28. for(int i=0; i<rev_graph[node].size(); i++){
  29.     int rev_sosed=rev_graph[node][i];
  30.     if(!visited[rev_sosed]){
  31.         rev_dfs(rev_sosed);
  32.     }
  33. }
  34. }
  35. int main()
  36. {
  37.  
  38.     cin>>m>>n;
  39.  
  40.     for(int i=0; i<n; i++){
  41.         int a, b;
  42.         cin>>a>>b;
  43.         graph[a].push_back(b);
  44.         rev_graph[b].push_back(a);
  45.  
  46.     }
  47.     memset(visited, false, sizeof visited);
  48.     for(int i=1; i<=m; i++){
  49.         if(!visited[i]){
  50.             dfs(i);
  51.         }
  52.     }
  53.     int br_kingdoms=0;
  54.     memset(visited, false, sizeof visited);
  55.     while(!s.empty()){
  56.         int node=s.top();
  57.         if(!visited[node]){
  58.             rev_dfs(node);
  59.             idx++;
  60.             br_kingdoms++;
  61. //            cout<<endl;
  62.         }
  63.         s.pop();
  64.        
  65.     }
  66.     cout<<br_kingdoms << endl;
  67.     for(int i=1; i<=m; i++){
  68.         cout<<niza[i] + 1<<" ";
  69.     }
  70.     return 0;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement