Advertisement
Josif_tepe

Untitled

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