Advertisement
JosepRivaille

P14952: Ordenació topològica

May 18th, 2016
908
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. using namespace std;
  5.  
  6.  
  7. typedef vector<int> Adj;
  8. typedef vector<Adj> Graph;
  9.  
  10.  
  11. void topological_sort(Graph &G, vector<int> & v)
  12. {
  13.   int n = G.size();
  14.   vector<int> sorted;
  15.   priority_queue<int, vector<int>, greater<int> > pQ;
  16.   for (int i = 0; i < n; ++i)
  17.     if (v[i] == 0) pQ.push(i);
  18.   while (!pQ.empty()) {
  19.     int new_node = pQ.top(); pQ.pop();
  20.     sorted.push_back(new_node);
  21.     for (int i = 0; i < G[new_node].size(); ++i) {
  22.       if (--v[G[new_node][i]] == 0) pQ.push(G[new_node][i]);
  23.     }
  24.   }
  25.   cout << sorted[0];
  26.   for (int i = 1; i < n; ++i) {
  27.     cout << " " << sorted[i];
  28.   } cout << endl;
  29. }
  30.  
  31. int main()
  32. {
  33.   int n, m, x, y;
  34.   while (cin >> n >> m) {
  35.     Graph G(n);
  36.     vector<int> v(n);
  37.     for (int i = 0; i < m; ++i) {
  38.       cin >> x >> y;
  39.       G[x].push_back(y);
  40.       ++v[y];
  41.     }
  42.     topological_sort(G, v);
  43.   }
  44. }
  45.  
  46. //JosepRivaille
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement