Advertisement
coloriot

HA32_Sort(14)

Nov 24th, 2024
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5.  
  6. int main() {
  7.     ios_base::sync_with_stdio(false);
  8.     cin.tie(NULL);
  9.  
  10.     int N, M;
  11.     cin >> N >> M;
  12.  
  13.     vector<vector<int> > adj(N + 1);
  14.     vector<int> in_degree(N + 1, 0);
  15.  
  16.     for (int i = 0; i < M; i++) {
  17.         int u, v;
  18.         cin >> u >> v;
  19.         adj[u].push_back(v);
  20.         in_degree[v]++;
  21.     }
  22.  
  23.     queue<int> q;
  24.     for (int u = 1; u <= N; u++) {
  25.         if (in_degree[u] == 0) {
  26.             q.push(u);
  27.         }
  28.     }
  29.  
  30.     vector<int> topo_order;
  31.     while (!q.empty()) {
  32.         int u = q.front();
  33.         q.pop();
  34.         topo_order.push_back(u);
  35.         for (int v : adj[u]) {
  36.             in_degree[v]--;
  37.             if (in_degree[v] == 0) {
  38.                 q.push(v);
  39.             }
  40.         }
  41.     }
  42.  
  43.     if (topo_order.size() == N) {
  44.         for (int u : topo_order) {
  45.             cout << u << ' ';
  46.         }
  47.         cout << endl;
  48.     } else {
  49.         cout << -1 << endl;
  50.     }
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement