fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define ll long long
  6. #define ull unsigned long long
  7.  
  8. #define fi first
  9. #define se second
  10.  
  11. #define FOR(x, y, z) for (int z = x; z < y; z++)
  12. #define FORD(x, y, z) for (int z = x; z > y; z--)
  13.  
  14. const int MAXN = 10;
  15.  
  16. vector<vector<int>> graph(MAXN);
  17. vector<int> ways_to_get(MAXN, 0);
  18.  
  19. vector<int> stacker;
  20. vector<bool> visited(MAXN, false);
  21. void topological_sort_with_DFS(int idx){
  22. if (visited[idx] == false){
  23. visited[idx] = true;
  24. for (auto child : graph[idx])
  25. topological_sort_with_DFS(child);
  26. stacker.push_back(idx);
  27. }
  28. }
  29.  
  30. int main(){
  31. ios::sync_with_stdio(0);
  32. cin.tie(nullptr); cout.tie(nullptr);
  33.  
  34. int n, m, from, to;
  35. cin >> n >> m;
  36.  
  37. FOR(0, m, i){
  38. cin >> from >> to;
  39. graph[from].push_back(to);
  40. }
  41.  
  42. FOR(1, n+1, i)
  43. topological_sort_with_DFS(i);
  44.  
  45. if ((int)stacker.size() == n)
  46. FORD(n-1, -1, i)
  47. cout << stacker[i] << " ";
  48. else
  49. cout << "Jest cykl, smutek, zal i zgrzytanie zebow :(\n";
  50.  
  51. return 0;
  52. }
  53.  
  54. /*
  55. Graf bez cyklu
  56. 5 6
  57. 1 2
  58. 1 3
  59. 3 2
  60. 2 4
  61. 2 5
  62. 4 5
  63.  
  64. Graf z cyklem
  65. 5 6
  66. 1 3
  67. 3 2
  68. 2 4
  69. 2 5
  70. 4 5
  71. 2 1
  72. */
Success #stdin #stdout 0s 5036KB
stdin
5 6
1 2
1 3
3 2
2 4
2 5
4 5
stdout
1 3 2 4 5