Advertisement
Josif_tepe

Untitled

Dec 26th, 2022
937
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <set>
  4. #include <cstring>
  5. #include <queue>
  6. #include <cmath>
  7. #include <algorithm>
  8. #include <stack>
  9. using namespace std;
  10. const int maxn = 1e5 + 10;
  11. int n, m;
  12. vector<int> graph[maxn];
  13. bool visited[maxn];
  14. stack<int> st;
  15. void topological_sort(int node) {
  16.     visited[node] = true;
  17.     cout << node + 1 << endl;
  18.     for(int i = 0; i < (int) graph[node].size(); i++) {
  19.         int neighbour = graph[node][i];
  20.         if(!visited[neighbour]) {
  21.             topological_sort(neighbour);
  22.         }
  23.     }
  24.    
  25.     st.push(node);
  26. }
  27. int main() {
  28.     cin >> n >> m;
  29.     for(int i = 0; i < m; i++) {
  30.         int a, b;
  31.         cin >> a>> b;
  32.         a--;
  33.         b--;
  34.         graph[a].push_back(b);
  35.     }
  36.     memset(visited, false, sizeof visited);
  37.     for(int i = 0; i < n; i++) {
  38.         if(!visited[i]) {
  39.             topological_sort(i);
  40.         }
  41.     }
  42.     while(!st.empty()) {
  43.         cout << st.top() + 1 << " ";
  44.         st.pop();
  45.     }
  46.     return 0;
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement