Advertisement
Josif_tepe

Untitled

May 18th, 2022
671
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 <cstring>
  4. #include <stack>
  5. using namespace std;
  6. typedef long long ll;
  7. int n, m;
  8. vector<int> graph[1005];
  9. bool visited[1005];
  10. stack<int> st;
  11. void dfs(int node) {
  12.     visited[node] = true;
  13.     for(int i = 0; i < graph[node].size(); i++) {
  14.         int sosed = graph[node][i];
  15.         if(!visited[sosed]) {
  16.             dfs(sosed);
  17.         }
  18.     }
  19.     st.push(node);
  20. }
  21. int main() {
  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.     memset(visited, false, sizeof visited);
  30.     for(int i = 0; i < n; i++) {
  31.         if(!visited[i]) {
  32.             dfs(i);
  33.         }
  34.     }
  35.     while(!st.empty()) {
  36.         cout << st.top() << " " ;
  37.         st.pop();
  38.     }
  39.     return 0;
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement