Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cassert>
- #include <vector>
- #include <queue>
- #include <algorithm>
- using std::cout;
- using std::endl;
- using std::vector;
- vector<int> wrong_topo_sort(const vector<vector<int>>& come_before) {
- vector<int> come_after_num(come_before.size());
- for (int s = 0; s < come_before.size(); s++) {
- for (int before : come_before[s]) {
- come_after_num[before]++;
- }
- }
- std::queue<int> frontier;
- for (int s = 0; s < come_before.size(); s++) {
- if (come_after_num[s] == 0) {
- frontier.push(s);
- }
- }
- int visited_num = 0;
- vector<int> order;
- while (!frontier.empty()) {
- int curr = frontier.front();
- frontier.pop();
- order.push_back(curr);
- visited_num++;
- for (int before : come_before[curr]) {
- if (--come_after_num[before] == 0) {
- frontier.push(before);
- }
- }
- }
- assert(visited_num == come_before.size());
- return order;
- }
- // sauce for toposort: https://www.geeksforgeeks.org/topological-sorting-indegree-based-solution/
- vector<int> valid_topo_sort(const vector<vector<int>>& neighbors) {
- vector<int> come_before(neighbors.size());
- for (int c = 0; c < neighbors.size(); c++) {
- for (int after : neighbors[c]) {
- come_before[after]++;
- }
- }
- std::queue<int> frontier;
- for (int s = 0; s < neighbors.size(); s++) {
- if (come_before[s] == 0) {
- frontier.push(s);
- }
- }
- int visited_num = 0;
- vector<int> order;
- while (!frontier.empty()) {
- int curr = frontier.front();
- frontier.pop();
- order.push_back(curr);
- visited_num++;
- for (int after : neighbors[curr]) {
- if (--come_before[after] == 0) {
- frontier.push(after);
- }
- }
- }
- assert(visited_num == neighbors.size());
- return order;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement