competitive-programming-library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub kmyk/competitive-programming-library

:heavy_check_mark: topological sort
(graph/topological_sort.hpp)

Depends on

Verified with

Code

#pragma once
#include <algorithm>
#include <functional>
#include <vector>
#include "../utils/macros.hpp"

/**
 * @brief topological sort
 * @return a list of vertices which sorted topologically
 * @note the empty list is returned if cycles exist
 * @note $O(V + E)$
 */
std::vector<int> topological_sort(const std::vector<std::vector<int> > & g) {
    int n = g.size();
    std::vector<int> order;
    std::vector<char> used(n);
    std::function<bool (int)> go = [&](int i) {
        used[i] = 1;  // in stack
        for (int j : g[i]) {
            if (used[j] == 1) return true;
            if (not used[j]) {
                if (go(j)) return true;
            }
        }
        used[i] = 2;  // completely used
        order.push_back(i);
        return false;
    };
    REP (i, n) if (not used[i]) {
        if (go(i)) return std::vector<int>();
    }
    std::reverse(ALL(order));
    return order;
}
#line 2 "graph/topological_sort.hpp"
#include <algorithm>
#include <functional>
#include <vector>
#line 2 "utils/macros.hpp"
#define REP(i, n) for (int i = 0; (i) < (int)(n); ++ (i))
#define REP3(i, m, n) for (int i = (m); (i) < (int)(n); ++ (i))
#define REP_R(i, n) for (int i = (int)(n) - 1; (i) >= 0; -- (i))
#define REP3R(i, m, n) for (int i = (int)(n) - 1; (i) >= (int)(m); -- (i))
#define ALL(x) std::begin(x), std::end(x)
#line 6 "graph/topological_sort.hpp"

/**
 * @brief topological sort
 * @return a list of vertices which sorted topologically
 * @note the empty list is returned if cycles exist
 * @note $O(V + E)$
 */
std::vector<int> topological_sort(const std::vector<std::vector<int> > & g) {
    int n = g.size();
    std::vector<int> order;
    std::vector<char> used(n);
    std::function<bool (int)> go = [&](int i) {
        used[i] = 1;  // in stack
        for (int j : g[i]) {
            if (used[j] == 1) return true;
            if (not used[j]) {
                if (go(j)) return true;
            }
        }
        used[i] = 2;  // completely used
        order.push_back(i);
        return false;
    };
    REP (i, n) if (not used[i]) {
        if (go(i)) return std::vector<int>();
    }
    std::reverse(ALL(order));
    return order;
}
Back to top page