Topological sort
(Mylib/Graph/TopologicalSort/topological_sort.cpp)
Operations
Requirements
Notes
Problems
References
Depends on
Code
#pragma once
#include <optional>
#include <queue>
#include <vector>
#include "Mylib/Graph/Template/graph.cpp"
namespace haar_lib {
template <typename T>
std::optional<std::vector<int>> topological_sort(const graph<T> &g) {
const int n = g.size();
std::vector<int> indeg(n);
for (int i = 0; i < n; ++i) {
for (auto &e : g[i]) {
++indeg[e.to];
}
}
std::queue<int> q;
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) q.push(i);
}
std::vector<int> ret;
while (not q.empty()) {
int cur = q.front();
q.pop();
ret.push_back(cur);
for (auto &e : g[cur]) {
--indeg[e.to];
if (indeg[e.to] == 0) {
q.push(e.to);
}
}
}
if ((int) ret.size() == n) {
return {ret};
} else {
return std::nullopt;
}
}
} // namespace haar_lib
#line 2 "Mylib/Graph/TopologicalSort/topological_sort.cpp"
#include <optional>
#include <queue>
#include <vector>
#line 2 "Mylib/Graph/Template/graph.cpp"
#include <iostream>
#line 4 "Mylib/Graph/Template/graph.cpp"
namespace haar_lib {
template <typename T>
struct edge {
int from, to;
T cost;
int index = -1;
edge() {}
edge(int from, int to, T cost) : from(from), to(to), cost(cost) {}
edge(int from, int to, T cost, int index) : from(from), to(to), cost(cost), index(index) {}
};
template <typename T>
struct graph {
using weight_type = T;
using edge_type = edge<T>;
std::vector<std::vector<edge<T>>> data;
auto& operator[](size_t i) { return data[i]; }
const auto& operator[](size_t i) const { return data[i]; }
auto begin() const { return data.begin(); }
auto end() const { return data.end(); }
graph() {}
graph(int N) : data(N) {}
bool empty() const { return data.empty(); }
int size() const { return data.size(); }
void add_edge(int i, int j, T w, int index = -1) {
data[i].emplace_back(i, j, w, index);
}
void add_undirected(int i, int j, T w, int index = -1) {
add_edge(i, j, w, index);
add_edge(j, i, w, index);
}
template <size_t I, bool DIRECTED = true, bool WEIGHTED = true>
void read(int M) {
for (int i = 0; i < M; ++i) {
int u, v;
std::cin >> u >> v;
u -= I;
v -= I;
T w = 1;
if (WEIGHTED) std::cin >> w;
if (DIRECTED)
add_edge(u, v, w, i);
else
add_undirected(u, v, w, i);
}
}
};
template <typename T>
using tree = graph<T>;
} // namespace haar_lib
#line 6 "Mylib/Graph/TopologicalSort/topological_sort.cpp"
namespace haar_lib {
template <typename T>
std::optional<std::vector<int>> topological_sort(const graph<T> &g) {
const int n = g.size();
std::vector<int> indeg(n);
for (int i = 0; i < n; ++i) {
for (auto &e : g[i]) {
++indeg[e.to];
}
}
std::queue<int> q;
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) q.push(i);
}
std::vector<int> ret;
while (not q.empty()) {
int cur = q.front();
q.pop();
ret.push_back(cur);
for (auto &e : g[cur]) {
--indeg[e.to];
if (indeg[e.to] == 0) {
q.push(e.to);
}
}
}
if ((int) ret.size() == n) {
return {ret};
} else {
return std::nullopt;
}
}
} // namespace haar_lib
Back to top page