Advertisement
Josif_tepe

Untitled

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