Advertisement
Josif_tepe

Untitled

Nov 13th, 2022
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <stack>
  5. #include <cstring>
  6. using namespace std;
  7. const int maxn = 3e5 + 10;
  8. int n, m;
  9. vector<int> graph[maxn];
  10. vector<int> reverse_graph[maxn];
  11. bool visited[maxn];
  12. stack<int> st;
  13. void topological_sort(int node) {
  14.     visited[node] = true;
  15.     for(int i = 0; i < (int) graph[node].size(); i++) {
  16.         int neigh = graph[node][i];
  17.         if(!visited[neigh]) {
  18.             topological_sort(neigh);
  19.         }
  20.     }
  21.     st.push(node);
  22. }
  23. vector<int> v;
  24. void dfs(int node) {
  25.     visited[node] = true;
  26.     v.push_back(node);
  27.     for(int i = 0; i < reverse_graph[node].size(); i++) {
  28.         int neigh = reverse_graph[node][i];
  29.         if(!visited[neigh]) {
  30.             dfs(neigh);
  31.         }
  32.     }
  33. }
  34. int main()
  35. {
  36.     cin >> n >> m;
  37.     for(int i = 0; i < m; i++) {
  38.         int a, b;
  39.         cin >> a >> b;
  40.         a--; b--;
  41.         graph[a].push_back(b);
  42.         reverse_graph[b].push_back(a);
  43.     }
  44.     memset(visited, false, sizeof visited);
  45.     for(int i = 0; i < n; i++) {
  46.         if(!visited[i]) {
  47.             topological_sort(i);
  48.         }
  49.     }
  50.     memset(visited, false, sizeof visited);
  51.     int cycles = 0;
  52.     vector<bool> special(n + 1, false);
  53.     while(!st.empty()) {
  54.         int node = st.top();
  55.         st.pop();
  56.         if(!visited[node]) {
  57.             v.clear();
  58.             dfs(node);
  59.             if(v.size() > 1) {
  60.                 for(int x : v) {
  61.                     special[x] = true;
  62.                 }
  63.             }
  64.         }
  65.     }
  66.     for(int i = 0; i < n; i++) {
  67.         cout << special[i] << " ";
  68.     }
  69.     return 0;
  70. }
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement