C++ Library for Competitive Programming
/*
* @title グラフ/トポロジカルソート
*
* verification-helper: IGNORE
* verification-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_B
*/
#include <iostream>
#include <vector>
#include "emthrm/graph/edge.hpp"
#include "emthrm/graph/topological_sort.hpp"
int main() {
int v, e;
std::cin >> v >> e;
std::vector<std::vector<emthrm::Edge<bool>>> graph(v);
while (e--) {
int s, t;
std::cin >> s >> t;
graph[s].emplace_back(s, t);
}
for (const int ans : emthrm::topological_sort(graph)) {
std::cout << ans << '\n';
}
return 0;
}
#line 1 "test/graph/topological_sort.test.cpp"
/*
* @title グラフ/トポロジカルソート
*
* verification-helper: IGNORE
* verification-helper: PROBLEM http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_B
*/
#include <iostream>
#include <vector>
#line 1 "include/emthrm/graph/edge.hpp"
/**
* @title 辺
*/
#ifndef EMTHRM_GRAPH_EDGE_HPP_
#define EMTHRM_GRAPH_EDGE_HPP_
#include <compare>
namespace emthrm {
template <typename CostType>
struct Edge {
CostType cost;
int src, dst;
explicit Edge(const int src, const int dst, const CostType cost = 0)
: cost(cost), src(src), dst(dst) {}
auto operator<=>(const Edge& x) const = default;
};
} // namespace emthrm
#endif // EMTHRM_GRAPH_EDGE_HPP_
#line 1 "include/emthrm/graph/topological_sort.hpp"
#include <queue>
#include <ranges>
#include <utility>
#line 8 "include/emthrm/graph/topological_sort.hpp"
#line 1 "include/emthrm/graph/edge.hpp"
/**
* @title 辺
*/
#ifndef EMTHRM_GRAPH_EDGE_HPP_
#define EMTHRM_GRAPH_EDGE_HPP_
#include <compare>
namespace emthrm {
template <typename CostType>
struct Edge {
CostType cost;
int src, dst;
explicit Edge(const int src, const int dst, const CostType cost = 0)
: cost(cost), src(src), dst(dst) {}
auto operator<=>(const Edge& x) const = default;
};
} // namespace emthrm
#endif // EMTHRM_GRAPH_EDGE_HPP_
#line 10 "include/emthrm/graph/topological_sort.hpp"
namespace emthrm {
template <typename CostType>
std::vector<int> topological_sort(
const std::vector<std::vector<Edge<CostType>>>& graph) {
const int n = graph.size();
std::vector<int> deg(n, 0);
for (const int e : graph
| std::views::join
| std::views::transform(&Edge<CostType>::dst)) {
++deg[e];
}
std::queue<int> que;
for (int i = 0; i < n; ++i) {
if (deg[i] == 0) que.emplace(i);
}
std::vector<int> res;
res.reserve(n);
while (!que.empty()) {
const int ver = que.front();
que.pop();
res.emplace_back(ver);
for (const int e : graph[ver]
| std::views::transform(&Edge<CostType>::dst)) {
if (--deg[e] == 0) que.emplace(e);
}
}
return std::cmp_equal(res.size(), n) ? res : std::vector<int>{};
}
} // namespace emthrm
#line 13 "test/graph/topological_sort.test.cpp"
int main() {
int v, e;
std::cin >> v >> e;
std::vector<std::vector<emthrm::Edge<bool>>> graph(v);
while (e--) {
int s, t;
std::cin >> s >> t;
graph[s].emplace_back(s, t);
}
for (const int ans : emthrm::topological_sort(graph)) {
std::cout << ans << '\n';
}
return 0;
}