Advertisement
Guest User

A (dfs)

a guest
Jan 19th, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int MAXN = 1e5 + 1;
  6.  
  7. vector <int> g[MAXN], ans;
  8. short col[MAXN]; // 0 - unvisited, 1 - processing, 2 - visited
  9.  
  10. bool dfs(int v) // Поиск в глубину (false - Ok, true - цикл)
  11. {
  12.     col[v] = 1;
  13.     for(int to : g[v])
  14.     {
  15.         if(col[to] == 1 or (col[to] == 0 and dfs(to)))
  16.            return true;
  17.     }
  18.     col[v] = 2;
  19.     ans.push_back(v);
  20.     return false;
  21. }
  22.  
  23. void topological_sort(int n)
  24. {
  25.     for(int i = 1; i <= n; i++)
  26.         if(col[i] == 0 and dfs(i))
  27.         {
  28.             ans.clear();
  29.             return;
  30.         }
  31.     reverse(ans.begin(), ans.end());
  32. }
  33.  
  34. int main()
  35. {
  36.     // Ускорение ввода
  37.     ios_base::sync_with_stdio(0);
  38.     cin.tie(0);
  39.     cout.tie(0);
  40.  
  41.     // Ввод/вывод из файла
  42.     freopen("input.txt", "r", stdin);
  43.     freopen("output.txt", "w", stdout);
  44.  
  45.     // Ввод
  46.     int n, m;
  47.     cin >> n >> m;
  48.     while(m--)
  49.     {
  50.         int a, b;
  51.         cin >> a >> b;
  52.         g[a].push_back(b);
  53.     }
  54.  
  55.     topological_sort(n); // Топологическая сортировка
  56.  
  57.     // Вывод
  58.     if(ans.empty())
  59.         cout << -1;
  60.     else
  61.     {
  62.         for(int i : ans)
  63.             cout << i << ' ';
  64.     }
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement