minimario

e-olymp: Find a Cycle

Jun 19th, 2015
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <algorithm>
  2. #define push_back pb
  3. #include <string>
  4. #include <vector>
  5. #include <iostream>
  6. using namespace std;
  7.  
  8. vector<int> g[100005];
  9. int parent[100005];
  10. int visited[100005];
  11. vector<int> path;
  12. vector<int> a;
  13.  
  14. int cycle, cycle_begin, cycle_end;
  15. void dfs(int s) {
  16.     visited[s] = 1;
  17.     for (int i=0; i < g[s].size(); i++) {
  18.         if (visited[g[s][i]] == 0) { parent[g[s][i]] = s; dfs(g[s][i]); }
  19.         else if (visited[g[s][i]] == 1) { cycle = 1; cycle_begin = g[s][i]; cycle_end = s; }
  20.     }
  21.     visited[s] = 2;
  22. }
  23.  
  24. int main() {
  25.     int n, m;
  26.     cin >> n >> m;
  27.     for (int i=0; i<m; i++) {
  28.         int a, b;
  29.         cin >> a >> b;
  30.         g[a].pb(b);
  31.     }
  32.  
  33.     for (int i=1; i < n+1; i++) {
  34.         if (cycle == 1) { break; }
  35.         if (visited[i] == 0) { dfs(i); }
  36.     }
  37.  
  38.     if (cycle == 1) {
  39.         cout << "YES" << endl;
  40.        
  41.         while (cycle_end != cycle_begin) {
  42.             a.pb(cycle_end);
  43.             cycle_end = parent[cycle_end];
  44.         }
  45.  
  46.         a.pb(cycle_begin);
  47.         reverse(a.begin(), a.end());
  48.  
  49.         for (int i=0; i < a.size(); i++) {
  50.             cout << a[i] << " ";
  51.         }
  52.     }
  53.  
  54.     else {
  55.         cout << "NO" << endl;
  56.     }
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment