Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e5 + 5; // Adjust based on constraints
- vector<int> adj[N];
- int indegree[N];
- vector<int> ans;
- void topological_sort(int n) {
- queue<int> q;
- // Push all nodes with indegree 0
- for (int i = 1; i <= n; i++) {
- if (indegree[i] == 0)
- q.push(i);
- }
- while (!q.empty()) {
- int u = q.front();
- q.pop();
- ans.push_back(u);
- for (int v : adj[u]) {
- indegree[v]--;
- if (indegree[v] == 0)
- q.push(v);
- }
- }
- // If topological sorting is not possible (i.e., cycle exists)
- if (ans.size() != n) {
- cout << "Cycle detected! Topological sorting not possible." << endl;
- return;
- }
- // Print topological order
- for (int node : ans)
- cout << node << " ";
- cout << endl;
- }
- int main() {
- int n, m;
- cin >> n >> m; // Number of nodes and edges
- // Read edges
- for (int i = 0; i < m; i++) {
- int u, v;
- cin >> u >> v;
- adj[u].push_back(v);
- indegree[v]++;
- }
- topological_sort(n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement