Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <vector>
- using namespace std;
- int n;
- vector<vector<int>> adj;
- vector<bool> vis;
- vector<int> L;
- void dfs(int u)
- {
- vis[u] = true;
- for(int v:adj[u]) if(!vis[v]) dfs(v);
- L.push_back(u);
- }
- void toposort()
- {
- for(int i=0;i<n;i++) if(!vis[i]) dfs(i);
- reverse(L.begin(), L.end());
- }
- int main()
- {
- n = 7;
- vis.resize(n);
- adj = {
- {1},
- {2,3,4},
- {4},
- {4},
- {5},
- {},
- {3}
- };
- toposort();
- cout << "Toposort: ";
- for(int e:L) cout << e << " ";
- cout << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment