BotByte

Print cycle in directed graph.cpp

Jun 1st, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. /*
  2.     CF 915D
  3.     Print cycle in directed graph
  4. */
  5.  
  6. #include <bits/stdc++.h>
  7.  
  8. using namespace std;
  9.  
  10. #define MAX 505
  11. int n, m;
  12. vector<int> adj[MAX];
  13. int cycle = -1;
  14. int vis[MAX], par[MAX];
  15. vector<int> V;
  16. int x, y;
  17.  
  18. void dfs2(int u)
  19. {
  20.     vis[u] = 1;
  21.     //cout << "u " << u << " " << vis[u] << endl;
  22.     for(int i=0; i<adj[u].size(); i++){
  23.         int v = adj[u][i];
  24.         if(u == x && v == y) continue;
  25.         //cout << "v " << v << " " << vis[v] << endl;
  26.         if(vis[v] == 1){
  27.             cycle = v;
  28.             return;
  29.         }
  30.         if(vis[v] == 0){
  31.             dfs2(v);
  32.         }
  33.     }
  34.     vis[u] = 2;
  35. }
  36.  
  37. void dfs(int u, int parent)
  38. {
  39.     vis[u] = 1;
  40.     par[u] = parent;
  41.     for(int i=0; i<adj[u].size(); i++){
  42.         int v = adj[u][i];
  43.         if((vis[v] == 1) && (cycle == -1)){
  44.             cycle = v;
  45.             V.push_back(cycle);
  46.             int node = u;
  47.             for(; node!= cycle; node=par[node]) V.push_back(node);
  48.             V.push_back(cycle);
  49.             reverse(V.begin(), V.end());
  50.             return;
  51.         }
  52.         if(vis[v] == 0){
  53.             dfs(v, u);
  54.         }
  55.     }
  56.     vis[u] = 2;
  57. }
  58.  
  59. int main()
  60. {
  61.     //freopen("in.txt", "r", stdin);
  62.     scanf("%d %d", &n, &m);
  63.     for(int i=0; i<m; i++){
  64.         int u, v;
  65.         scanf("%d %d", &u, &v);
  66.         adj[u].push_back(v);
  67.     }
  68.     memset(vis, 0, sizeof vis);
  69.     for(int i=1; i<=n; i++){
  70.         if(vis[i] == 0){
  71.             dfs(i, -1);
  72.             if(cycle != -1) break;
  73.         }
  74.     }
  75.     if(cycle == -1){
  76.         cout << "YES";
  77.         return 0;
  78.     }
  79.     memset(vis, 0, sizeof vis);
  80.     for(int i=0; i<V.size()-1; i++){
  81.         x = V[i], y = V[i+1], cycle = -1;
  82.         memset(vis, 0, sizeof vis);
  83.         for(int j=1; j<=n; j++){
  84.             if(vis[j] == 0) dfs2(j);
  85.         }
  86.         if(cycle == -1){
  87.             cout << "YES";
  88.             return 0;
  89.         }
  90.     }
  91.     cout << "NO";
  92. }
Advertisement
Add Comment
Please, Sign In to add comment