Advertisement
mfgnik

Untitled

Nov 24th, 2020
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <algorithm>
  5.  
  6.  
  7. using namespace std;
  8.  
  9. using ll = long long;
  10.  
  11. int cycle_start = -1, cycle_end;
  12.  
  13. bool dfs(int v, const vector<vector<int>> &a, vector<int> &used, map<int, int>& p) {
  14.     used[v] = 1;
  15.     for (auto to : a[v]) {
  16.         if (used[to] == 0) {
  17.             p[to] = v;
  18.             if (dfs(to, a, used, p)) {
  19.                 return true;
  20.             }
  21.         } else if (used[to] == 1) {
  22.             cycle_start = v;
  23.             cycle_end = to;
  24.             return true;
  25.         }
  26.     }
  27.     used[v] = 2;
  28.     return false;
  29. }
  30.  
  31. int main() {
  32.     int n, m;
  33.     cin >> n >> m;
  34.     int u, v;
  35.     vector<vector<int>> a(n);
  36.     for (int to = 0; to < m; ++to) {
  37.         cin >> v >> u;
  38.         a[u - 1].push_back(v - 1);
  39.     }
  40.     vector<int> used(n);
  41.     map<int, int> p;
  42.     vector<int> f;
  43.     for (int to = 0; to < n; ++to) {
  44.             if(dfs(to, a, used, p)) {
  45.                 break;
  46.             }
  47.  
  48.     }
  49.  
  50.     if  (cycle_start == -1) {
  51.         std::cout << -1;
  52.         return 0;
  53.     }
  54.     vector<int> cycle;
  55.     cycle.push_back (cycle_start);
  56.     for (int v=cycle_end; v!=cycle_start && v.co; v=p[v]) {
  57.         cycle.push_back (v);
  58.         std::cout << v << "\n";
  59.     }
  60.     cycle.push_back (cycle_start);
  61.     reverse (cycle.begin(), cycle.end());
  62.     std::cout << cycle.size() << "\n";
  63.     for (auto v: cycle) {
  64.         std::cout << v << " ";
  65.     }
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement