Advertisement
Araf_12

topological_sorting(BFS)

Apr 1st, 2025
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 1e5 + 5; // Adjust based on constraints
  5. vector<int> adj[N];
  6. int indegree[N];
  7. vector<int> ans;
  8.  
  9. void topological_sort(int n) {
  10.     queue<int> q;
  11.    
  12.     // Push all nodes with indegree 0
  13.     for (int i = 1; i <= n; i++) {
  14.         if (indegree[i] == 0)
  15.             q.push(i);
  16.     }
  17.  
  18.     while (!q.empty()) {
  19.         int u = q.front();
  20.         q.pop();
  21.         ans.push_back(u);
  22.  
  23.         for (int v : adj[u]) {
  24.             indegree[v]--;
  25.             if (indegree[v] == 0)
  26.                 q.push(v);
  27.         }
  28.     }
  29.  
  30.     // If topological sorting is not possible (i.e., cycle exists)
  31.     if (ans.size() != n) {
  32.         cout << "Cycle detected! Topological sorting not possible." << endl;
  33.         return;
  34.     }
  35.  
  36.     // Print topological order
  37.     for (int node : ans)
  38.         cout << node << " ";
  39.     cout << endl;
  40. }
  41.  
  42. int main() {
  43.     int n, m;
  44.     cin >> n >> m; // Number of nodes and edges
  45.  
  46.     // Read edges
  47.     for (int i = 0; i < m; i++) {
  48.         int u, v;
  49.         cin >> u >> v;
  50.         adj[u].push_back(v);
  51.         indegree[v]++;
  52.     }
  53.  
  54.     topological_sort(n);
  55.  
  56.     return 0;
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement