Advertisement
SansPapyrus683

Topological Sort Comparison

Dec 22nd, 2021
1,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <iostream>
  2. #include <cassert>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6.  
  7. using std::cout;
  8. using std::endl;
  9. using std::vector;
  10.  
  11. vector<int> wrong_topo_sort(const vector<vector<int>>& come_before) {
  12.     vector<int> come_after_num(come_before.size());
  13.     for (int s = 0; s < come_before.size(); s++) {
  14.         for (int before : come_before[s]) {
  15.             come_after_num[before]++;
  16.         }
  17.     }
  18.     std::queue<int> frontier;
  19.     for (int s = 0; s < come_before.size(); s++) {
  20.         if (come_after_num[s] == 0) {
  21.             frontier.push(s);
  22.         }
  23.     }
  24.  
  25.     int visited_num = 0;
  26.     vector<int> order;
  27.     while (!frontier.empty()) {
  28.         int curr = frontier.front();
  29.         frontier.pop();
  30.         order.push_back(curr);
  31.         visited_num++;
  32.         for (int before : come_before[curr]) {
  33.             if (--come_after_num[before] == 0) {
  34.                 frontier.push(before);
  35.             }
  36.         }
  37.     }
  38.     assert(visited_num == come_before.size());
  39.     return order;
  40. }
  41.  
  42. // sauce for toposort: https://www.geeksforgeeks.org/topological-sorting-indegree-based-solution/
  43. vector<int> valid_topo_sort(const vector<vector<int>>& neighbors) {
  44.     vector<int> come_before(neighbors.size());
  45.     for (int c = 0; c < neighbors.size(); c++) {
  46.         for (int after : neighbors[c]) {
  47.             come_before[after]++;
  48.         }
  49.     }
  50.     std::queue<int> frontier;
  51.     for (int s = 0; s < neighbors.size(); s++) {
  52.         if (come_before[s] == 0) {
  53.             frontier.push(s);
  54.         }
  55.     }
  56.     int visited_num = 0;
  57.     vector<int> order;
  58.     while (!frontier.empty()) {
  59.         int curr = frontier.front();
  60.         frontier.pop();
  61.         order.push_back(curr);
  62.         visited_num++;
  63.         for (int after : neighbors[curr]) {
  64.             if (--come_before[after] == 0) {
  65.                 frontier.push(after);
  66.             }
  67.         }
  68.     }
  69.     assert(visited_num == neighbors.size());
  70.     return order;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement