fork download
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. #define ll long long
  5. #define ld long double
  6. #define N 1000000
  7. const ll MOD = 1e9 + 7;
  8.  
  9. ll i, j, k, n, m, u, v;
  10. vector<ll> adj[N];
  11. ll vis[N] = {0};
  12. bool cycle = false;
  13. vector<ll> ans;
  14.  
  15. void dfs(ll x)
  16. {
  17. vis[x] = 1;
  18. for (auto it : adj[x])
  19. {
  20. if (!vis[it])
  21. dfs(it);
  22. else if (vis[it] == 1)
  23. cycle = true;
  24. }
  25. vis[x] = 2;
  26. ans.push_back(x);
  27. }
  28.  
  29. void top_sort(ll n)
  30. {
  31. for (i = 1; i <= n; i++)
  32. {
  33. if (!vis[i])
  34. dfs(i);
  35. }
  36. reverse(ans.begin(), ans.end());
  37. }
  38.  
  39. signed main()
  40. {
  41. ios::sync_with_stdio(false);
  42. cin.tie(nullptr);
  43. cout.tie(nullptr);
  44.  
  45. cin >> n >> m;
  46. for (i = 0; i < m; i++)
  47. {
  48. cin >> u >> v;
  49. adj[u].push_back(v);
  50. }
  51.  
  52. top_sort(n);
  53.  
  54. if (cycle)
  55. cout << "Sandro fails.";
  56. else
  57. {
  58. for (auto it : ans)
  59. cout << it << ' ';
  60. cout << '\n';
  61. }
  62. }
Success #stdin #stdout 0.02s 27956KB
stdin
Standard input is empty
stdout