This documentation is automatically generated by online-judge-tools/verification-helper
有向グラフのトポロジカル順序を求める。 閉路があるときは空配列を返す。 計算量は $O(N + M)$。
vector<int> topological_sort(const vector<vector<int>>& g)
g のトポロジカル順序を返す。DAG でなければ空配列を返すg[v] に v -> to を入れて使う。
順序は DFS の帰りがけ順を反転したものになる。
vector<int> topological_sort(const vector<vector<int>> &g) {
int n = g.size();
vector<int> state(n), ord;
ord.reserve(n);
auto dfs = [&](auto &&self, int v) -> bool {
state[v] = 1;
for (auto &&to : g[v]) {
if (state[to] == 1) return false;
if (state[to] == 0 && !self(self, to)) return false;
}
state[v] = 2;
ord.emplace_back(v);
return true;
};
for (int i = 0; i < n; ++i) {
if (state[i] == 0 && !dfs(dfs, i)) return {};
}
reverse(ord.begin(), ord.end());
return ord;
}
/**
* @brief トポロジカルソート(Topological Sort)
*/#line 1 "graph/topological_sort.cpp"
vector<int> topological_sort(const vector<vector<int>> &g) {
int n = g.size();
vector<int> state(n), ord;
ord.reserve(n);
auto dfs = [&](auto &&self, int v) -> bool {
state[v] = 1;
for (auto &&to : g[v]) {
if (state[to] == 1) return false;
if (state[to] == 0 && !self(self, to)) return false;
}
state[v] = 2;
ord.emplace_back(v);
return true;
};
for (int i = 0; i < n; ++i) {
if (state[i] == 0 && !dfs(dfs, i)) return {};
}
reverse(ord.begin(), ord.end());
return ord;
}
/**
* @brief トポロジカルソート(Topological Sort)
*/