urmisaha

Samsung-Print any Cycle in a Directed Graph

Nov 5th, 2019
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. // Input:
  6. // 8 9
  7. // 3 1 2 5 5 4 3 4 2 3 5 6 6 7 7 8 8 6
  8.  
  9. // Output:
  10. // 6 7 8
  11.  
  12. int n, m, x, y, flag, node, bridge;
  13. int g[10][10];
  14. char color[10];
  15. int ans[10];
  16.  
  17. int dfs(int x){
  18.     if(color[x] == 'w'){
  19.         color[x] = 'g';
  20.         for(int i=1; i<=n; ++i){
  21.             if(g[x][i]){
  22.                 if(color[i] == 'g'){
  23.                     flag = 1;
  24.                     bridge = i;
  25.                     ans[i] = 1;
  26.                     return 1;
  27.                 }
  28.                 else if(color[i] == 'w' && dfs(i)){
  29.                     if(flag)
  30.                         ans[i] = 1;
  31.                     if(i == bridge)
  32.                         flag = 0;
  33.                     return 1;
  34.                 }
  35.             }
  36.         }
  37.     }
  38.     color[x] = 'b';
  39.     return 0;
  40. }
  41.  
  42. int main() {
  43.     cin>>n>>m;
  44.     for(int i=0; i<m; ++i){
  45.         cin>>x>>y;
  46.         g[x][y] = 1;
  47.     }
  48.     for(int i=1; i<=n; ++i)
  49.         color[i] = 'w';
  50.     int found = 0;
  51.     for(int i=1; i<=n; ++i){
  52.         if(color[i] == 'w' && dfs(i)){
  53.             found = 1;
  54.             for(int i=1; i<=n; ++i)
  55.                 if(ans[i])
  56.                     cout<<i<<" ";
  57.             break;
  58.         }
  59.        
  60.     }
  61.     if(!found)
  62.         cout<<0<<endl;
  63.     return 0;
  64. }
Add Comment
Please, Sign In to add comment