Advertisement
Josif_tepe

Untitled

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