This documentation is automatically generated by competitive-verifier/competitive-verifier
#include "graph/others/topological-sort.hpp"DAG(閉路のない有向グラフ) が与えられたとき、トポロジカルソートする。
入次数 $0$ の頂点から消すことを繰り返す。
vector<int> topological_sort(const Graph<T>& g)
DAG g をトポロジカルソートして、その頂点の順序を返す。
$O(E + V)$
#pragma once
#include <stack>
#include <vector>
#include "../graph-template.hpp"
/**
* @brief Topological Sort(トポロジカルソート)
*
*/
template <typename T>
std::vector<int> topological_sort(const Graph<T>& g) {
const int N = (int)g.size();
std::vector<int> deg(N);
for (int i = 0; i < N; i++) {
for (auto& to : g[i]) ++deg[to];
}
std::stack<int> st;
for (int i = 0; i < N; i++) {
if (deg[i] == 0) st.emplace(i);
}
std::vector<int> ord;
while (!st.empty()) {
auto p = st.top();
st.pop();
ord.emplace_back(p);
for (auto& to : g[p]) {
if (--deg[to] == 0) st.emplace(to);
}
}
return ord;
}
#line 2 "graph/others/topological-sort.hpp"
#include <stack>
#include <vector>
#line 2 "graph/graph-template.hpp"
#include <cstddef>
#include <iostream>
#line 6 "graph/graph-template.hpp"
template <typename T = int>
struct Edge {
int from, to;
T cost;
int idx;
Edge() = default;
Edge(int from, int to, T cost = 1, int idx = -1)
: from(from), to(to), cost(cost), idx(idx) {}
operator int() const { return to; }
};
template <typename T = int>
struct Graph {
std::vector<std::vector<Edge<T> > > g;
int es;
Graph() = default;
explicit Graph(int n) : g(n), es(0) {}
std::size_t size() const { return g.size(); }
void add_directed_edge(int from, int to, T cost = 1) {
g[from].emplace_back(from, to, cost, es++);
}
void add_edge(int from, int to, T cost = 1) {
g[from].emplace_back(from, to, cost, es);
g[to].emplace_back(to, from, cost, es++);
}
void read(int M, int padding = -1, bool weighted = false,
bool directed = false) {
for (int i = 0; i < M; i++) {
int a, b;
std::cin >> a >> b;
a += padding;
b += padding;
T c = T(1);
if (weighted) std::cin >> c;
if (directed)
add_directed_edge(a, b, c);
else
add_edge(a, b, c);
}
}
inline std::vector<Edge<T> >& operator[](const int& k) { return g[k]; }
inline const std::vector<Edge<T> >& operator[](const int& k) const {
return g[k];
}
};
template <typename T = int>
using Edges = std::vector<Edge<T> >;
#line 7 "graph/others/topological-sort.hpp"
/**
* @brief Topological Sort(トポロジカルソート)
*
*/
template <typename T>
std::vector<int> topological_sort(const Graph<T>& g) {
const int N = (int)g.size();
std::vector<int> deg(N);
for (int i = 0; i < N; i++) {
for (auto& to : g[i]) ++deg[to];
}
std::stack<int> st;
for (int i = 0; i < N; i++) {
if (deg[i] == 0) st.emplace(i);
}
std::vector<int> ord;
while (!st.empty()) {
auto p = st.top();
st.pop();
ord.emplace_back(p);
for (auto& to : g[p]) {
if (--deg[to] == 0) st.emplace(to);
}
}
return ord;
}