fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void fastio() {
  5. ios_base::sync_with_stdio(false);
  6. cin.tie(nullptr);
  7. cout.tie(nullptr);
  8. }
  9.  
  10. int n, m;
  11. vector<vector<int>> adjList;
  12. vector<bool> vis;
  13. vector<int> topo;
  14.  
  15. void dfs(int node) {
  16. vis[node] = true;
  17. for (auto& v : adjList[node])
  18. if (!vis[v])
  19. dfs(v);
  20. topo.push_back(node);
  21. }
  22.  
  23. void solve() {
  24. while (cin >> n >> m) {
  25. if (n == 0 && m == 0)
  26. return;
  27.  
  28. adjList.assign(n + 1, vector<int>());
  29. vis.assign(n + 1, false);
  30. topo.clear();
  31. for (int i = 0; i < m; ++i) {
  32. int u, v;
  33. cin >> u >> v;
  34. adjList[u].push_back(v);
  35. }
  36.  
  37. for (int i = 1; i <= n; ++i)
  38. if (!vis[i])
  39. dfs(i);
  40.  
  41. reverse(topo.begin(), topo.end());
  42. for (auto& t : topo)
  43. cout << t << ' ';
  44. cout << '\n';
  45. }
  46. }
  47.  
  48. int main() {
  49. fastio();
  50. solve();
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Standard output is empty