786 lines
26 KiB
C++
786 lines
26 KiB
C++
#pragma once
|
|
|
|
#include <Void/Math/Numeric.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <concepts>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <limits>
|
|
#include <ranges>
|
|
#include <span>
|
|
#include <stop_token>
|
|
#include <string>
|
|
#include <type_traits>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::Algorithms
|
|
{
|
|
|
|
struct WorkLimits {
|
|
std::size_t max_vertices{1'000'000};
|
|
std::size_t max_steps{16'000'000};
|
|
std::size_t max_scratch_bytes{64ULL * 1024ULL * 1024ULL};
|
|
std::size_t cancel_check_interval{1024};
|
|
};
|
|
|
|
struct AlgorithmError {
|
|
enum class Code {
|
|
invalid_input,
|
|
invalid_vertex,
|
|
limit_exceeded,
|
|
overflow,
|
|
cancelled,
|
|
concurrent_modification,
|
|
cycle_detected
|
|
};
|
|
|
|
Code code{Code::invalid_input};
|
|
std::string message{};
|
|
std::vector<std::size_t> cycle{};
|
|
};
|
|
|
|
struct TraversalResult {
|
|
static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();
|
|
|
|
std::vector<std::size_t> order{};
|
|
std::vector<std::size_t> parent{};
|
|
std::vector<std::size_t> depth{};
|
|
};
|
|
|
|
struct ShortestPathResult {
|
|
static constexpr std::size_t npos = std::numeric_limits<std::size_t>::max();
|
|
|
|
bool found{false};
|
|
std::size_t distance{npos};
|
|
std::vector<std::size_t> path{};
|
|
};
|
|
|
|
struct Topology {
|
|
std::vector<std::size_t> order{};
|
|
std::vector<std::size_t> position{};
|
|
};
|
|
|
|
template <typename G>
|
|
concept IndexedGraphView = requires(const G& g, std::size_t u) {
|
|
{ g.vertex_count() } -> std::convertible_to<std::size_t>;
|
|
{ g.neighbors(u) } -> std::ranges::input_range;
|
|
requires std::convertible_to<std::ranges::range_value_t<decltype(g.neighbors(u))>,
|
|
std::size_t>;
|
|
};
|
|
|
|
template <typename G>
|
|
concept HasVersionStamp = requires(const G& g) {
|
|
{ g.version() };
|
|
{ g.version() == g.version() } -> std::convertible_to<bool>;
|
|
};
|
|
|
|
class AdjacencyView
|
|
{
|
|
public:
|
|
AdjacencyView() noexcept = default;
|
|
|
|
explicit AdjacencyView(std::span<const std::vector<std::size_t>> lists) noexcept
|
|
: lists_(lists)
|
|
{
|
|
}
|
|
|
|
explicit AdjacencyView(const std::vector<std::vector<std::size_t>>& lists) noexcept
|
|
: lists_(lists)
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] static std::expected<AdjacencyView, AlgorithmError>
|
|
try_from_csr(std::span<const std::size_t> offsets,
|
|
std::span<const std::size_t> edges)
|
|
{
|
|
if (offsets.empty()) {
|
|
if (!edges.empty()) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_input,
|
|
"CSR edges present with empty offsets"}};
|
|
}
|
|
return AdjacencyView{};
|
|
}
|
|
if (offsets.front() != 0) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_input,
|
|
"CSR offsets must start at 0"}};
|
|
}
|
|
for (std::size_t i = 0; i + 1 < offsets.size(); ++i) {
|
|
if (offsets[i] > offsets[i + 1]) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_input,
|
|
"CSR offsets must be monotonically non-decreasing"}};
|
|
}
|
|
}
|
|
if (offsets.back() > edges.size()) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_input,
|
|
"CSR final offset exceeds edges span size"}};
|
|
}
|
|
return AdjacencyView{offsets, edges};
|
|
}
|
|
|
|
[[nodiscard]] std::size_t vertex_count() const noexcept
|
|
{
|
|
if (is_csr_) {
|
|
return csr_offsets_.empty() ? 0 : (csr_offsets_.size() - 1);
|
|
}
|
|
return lists_.size();
|
|
}
|
|
|
|
[[nodiscard]] std::span<const std::size_t> neighbors(std::size_t u) const noexcept
|
|
{
|
|
if (is_csr_) {
|
|
if (u + 1 >= csr_offsets_.size()) {
|
|
return {};
|
|
}
|
|
const std::size_t begin = csr_offsets_[u];
|
|
const std::size_t end = csr_offsets_[u + 1];
|
|
if (begin > end || end > csr_edges_.size()) {
|
|
return {};
|
|
}
|
|
return csr_edges_.subspan(begin, end - begin);
|
|
}
|
|
if (u >= lists_.size()) {
|
|
return {};
|
|
}
|
|
return lists_[u];
|
|
}
|
|
|
|
private:
|
|
AdjacencyView(std::span<const std::size_t> offsets,
|
|
std::span<const std::size_t> edges) noexcept
|
|
: csr_offsets_(offsets)
|
|
, csr_edges_(edges)
|
|
, is_csr_(true)
|
|
{
|
|
}
|
|
|
|
std::span<const std::vector<std::size_t>> lists_{};
|
|
std::span<const std::size_t> csr_offsets_{};
|
|
std::span<const std::size_t> csr_edges_{};
|
|
bool is_csr_{false};
|
|
};
|
|
|
|
namespace detail
|
|
{
|
|
|
|
template <typename T>
|
|
[[nodiscard]] inline bool valid_vertex_index(T raw, std::size_t vertex_count) noexcept
|
|
{
|
|
if constexpr (std::is_signed_v<T>) {
|
|
if (raw < 0) {
|
|
return false;
|
|
}
|
|
}
|
|
return std::cmp_less(raw, vertex_count);
|
|
}
|
|
|
|
[[nodiscard]] inline std::expected<std::size_t, AlgorithmError>
|
|
checked_scratch_bytes(std::size_t count,
|
|
std::size_t bytes_per_element,
|
|
const WorkLimits& limits)
|
|
{
|
|
const auto prod = Void::Numeric::checked_mul(count, bytes_per_element);
|
|
if (!prod.has_value()) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::overflow,
|
|
"Scratch byte budget multiplication overflowed"}};
|
|
}
|
|
if (*prod > limits.max_scratch_bytes) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"Estimated scratch memory exceeds WorkLimits::max_scratch_bytes"}};
|
|
}
|
|
return *prod;
|
|
}
|
|
|
|
template <typename G>
|
|
struct VersionSnapshot {
|
|
};
|
|
|
|
template <typename G>
|
|
requires HasVersionStamp<G>
|
|
struct VersionSnapshot<G> {
|
|
using type = std::remove_cvref_t<decltype(std::declval<const G&>().version())>;
|
|
type initial{};
|
|
};
|
|
|
|
template <IndexedGraphView G>
|
|
[[nodiscard]] inline VersionSnapshot<G> capture_version(const G& g)
|
|
{
|
|
if constexpr (HasVersionStamp<G>) {
|
|
return VersionSnapshot<G>{g.version()};
|
|
} else {
|
|
(void)g;
|
|
return VersionSnapshot<G>{};
|
|
}
|
|
}
|
|
|
|
template <IndexedGraphView G>
|
|
[[nodiscard]] inline std::expected<void, AlgorithmError>
|
|
check_state(const G& g,
|
|
const VersionSnapshot<G>& snap,
|
|
const std::stop_token& stop_token)
|
|
{
|
|
if (stop_token.stop_requested()) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::cancelled,
|
|
"Algorithm cancelled via stop_token"}};
|
|
}
|
|
if constexpr (HasVersionStamp<G>) {
|
|
if (!(g.version() == snap.initial)) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::concurrent_modification,
|
|
"Graph version changed during traversal"}};
|
|
}
|
|
} else {
|
|
(void)g;
|
|
(void)snap;
|
|
}
|
|
return {};
|
|
}
|
|
|
|
[[nodiscard]] inline std::expected<void, AlgorithmError>
|
|
advance_step(std::size_t& steps, const WorkLimits& limits)
|
|
{
|
|
if (steps >= limits.max_steps) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"Step count exceeded WorkLimits::max_steps"}};
|
|
}
|
|
const auto next = Void::Numeric::checked_add(steps, std::size_t{1});
|
|
if (!next.has_value()) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::overflow,
|
|
"Step counter overflowed"}};
|
|
}
|
|
steps = *next;
|
|
return {};
|
|
}
|
|
|
|
template <IndexedGraphView G>
|
|
[[nodiscard]] inline std::expected<void, AlgorithmError>
|
|
step_and_maybe_check(const G& g,
|
|
const VersionSnapshot<G>& snap,
|
|
const std::stop_token& stop_token,
|
|
std::size_t& steps,
|
|
const WorkLimits& limits)
|
|
{
|
|
if (auto s = advance_step(steps, limits); !s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
if (limits.cancel_check_interval > 0 &&
|
|
(steps % limits.cancel_check_interval) == 0) {
|
|
if (auto c = check_state(g, snap, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
|
|
} // namespace detail
|
|
|
|
template <IndexedGraphView G>
|
|
[[nodiscard]] std::expected<TraversalResult, AlgorithmError>
|
|
bfs(const G& graph,
|
|
std::size_t start,
|
|
const WorkLimits& limits = {},
|
|
std::stop_token stop_token = {})
|
|
{
|
|
const auto version = detail::capture_version(graph);
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
|
|
const std::size_t n = static_cast<std::size_t>(graph.vertex_count());
|
|
if (n > limits.max_vertices) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"Vertex count exceeds WorkLimits::max_vertices"}};
|
|
}
|
|
if (start >= n) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Start vertex index is out of range"}};
|
|
}
|
|
|
|
constexpr std::size_t kPerVertexBytes =
|
|
4 * sizeof(std::size_t) + sizeof(std::uint8_t);
|
|
if (auto s = detail::checked_scratch_bytes(n, kPerVertexBytes, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
|
|
std::vector<std::uint8_t> visited(n, 0);
|
|
std::vector<std::size_t> queue;
|
|
queue.reserve(n);
|
|
|
|
TraversalResult result;
|
|
result.parent.assign(n, TraversalResult::npos);
|
|
result.depth.assign(n, TraversalResult::npos);
|
|
result.order.reserve(n);
|
|
|
|
visited[start] = 1;
|
|
result.depth[start] = 0;
|
|
queue.push_back(start);
|
|
|
|
std::size_t steps = 0;
|
|
std::size_t head = 0;
|
|
while (head < queue.size()) {
|
|
const std::size_t u = queue[head++];
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
result.order.push_back(u);
|
|
|
|
for (const auto raw_v : graph.neighbors(u)) {
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
if (!detail::valid_vertex_index(raw_v, n)) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Neighbor vertex index out of range"}};
|
|
}
|
|
const std::size_t v = static_cast<std::size_t>(raw_v);
|
|
if (!visited[v]) {
|
|
visited[v] = 1;
|
|
result.parent[v] = u;
|
|
result.depth[v] = result.depth[u] + 1;
|
|
queue.push_back(v);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
return result;
|
|
}
|
|
|
|
template <IndexedGraphView G>
|
|
[[nodiscard]] std::expected<TraversalResult, AlgorithmError>
|
|
dfs(const G& graph,
|
|
std::size_t start,
|
|
const WorkLimits& limits = {},
|
|
std::stop_token stop_token = {})
|
|
{
|
|
const auto version = detail::capture_version(graph);
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
|
|
const std::size_t n = static_cast<std::size_t>(graph.vertex_count());
|
|
if (n > limits.max_vertices) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"Vertex count exceeds WorkLimits::max_vertices"}};
|
|
}
|
|
if (start >= n) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Start vertex index is out of range"}};
|
|
}
|
|
|
|
struct Frame {
|
|
std::size_t vertex;
|
|
std::size_t parent;
|
|
std::size_t depth;
|
|
};
|
|
|
|
constexpr std::size_t kBasePerVertexBytes =
|
|
3 * sizeof(std::size_t) + sizeof(std::uint8_t);
|
|
const auto base_scratch =
|
|
detail::checked_scratch_bytes(n, kBasePerVertexBytes, limits);
|
|
if (!base_scratch.has_value()) {
|
|
return std::unexpected{std::move(base_scratch.error())};
|
|
}
|
|
|
|
std::vector<std::uint8_t> visited(n, 0);
|
|
std::vector<Frame> stack;
|
|
std::vector<std::size_t> scratch_neighbors;
|
|
|
|
TraversalResult result;
|
|
result.parent.assign(n, TraversalResult::npos);
|
|
result.depth.assign(n, TraversalResult::npos);
|
|
result.order.reserve(n);
|
|
|
|
if (*base_scratch + sizeof(Frame) > limits.max_scratch_bytes) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"DFS stack scratch memory exceeds WorkLimits::max_scratch_bytes"}};
|
|
}
|
|
stack.push_back(Frame{start, TraversalResult::npos, 0});
|
|
|
|
std::size_t steps = 0;
|
|
while (!stack.empty()) {
|
|
const Frame cur = stack.back();
|
|
stack.pop_back();
|
|
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
if (visited[cur.vertex]) {
|
|
continue;
|
|
}
|
|
visited[cur.vertex] = 1;
|
|
result.parent[cur.vertex] = cur.parent;
|
|
result.depth[cur.vertex] = cur.depth;
|
|
result.order.push_back(cur.vertex);
|
|
|
|
scratch_neighbors.clear();
|
|
for (const auto raw_v : graph.neighbors(cur.vertex)) {
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
if (!detail::valid_vertex_index(raw_v, n)) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Neighbor vertex index out of range"}};
|
|
}
|
|
const std::size_t v = static_cast<std::size_t>(raw_v);
|
|
if (!visited[v]) {
|
|
scratch_neighbors.push_back(v);
|
|
const auto dyn_bytes = Void::Numeric::checked_mul(
|
|
stack.size() + scratch_neighbors.size(), sizeof(Frame));
|
|
if (!dyn_bytes.has_value()) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::overflow,
|
|
"DFS stack byte calculation overflowed"}};
|
|
}
|
|
if (*base_scratch + *dyn_bytes > limits.max_scratch_bytes) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"DFS stack scratch memory exceeds WorkLimits::max_scratch_bytes"}};
|
|
}
|
|
}
|
|
}
|
|
for (auto it = scratch_neighbors.rbegin(); it != scratch_neighbors.rend(); ++it) {
|
|
stack.push_back(Frame{*it, cur.vertex, cur.depth + 1});
|
|
}
|
|
}
|
|
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
return result;
|
|
}
|
|
|
|
template <IndexedGraphView G>
|
|
[[nodiscard]] std::expected<ShortestPathResult, AlgorithmError>
|
|
shortest_path_unweighted(const G& graph,
|
|
std::size_t start,
|
|
std::size_t target,
|
|
const WorkLimits& limits = {},
|
|
std::stop_token stop_token = {})
|
|
{
|
|
const auto version = detail::capture_version(graph);
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
|
|
const std::size_t n = static_cast<std::size_t>(graph.vertex_count());
|
|
if (n > limits.max_vertices) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"Vertex count exceeds WorkLimits::max_vertices"}};
|
|
}
|
|
if (start >= n || target >= n) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Start or target vertex index is out of range"}};
|
|
}
|
|
|
|
if (start == target) {
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
return ShortestPathResult{
|
|
.found = true,
|
|
.distance = 0,
|
|
.path = {start},
|
|
};
|
|
}
|
|
|
|
constexpr std::size_t kPerVertexBytes =
|
|
2 * sizeof(std::size_t) + sizeof(std::uint8_t);
|
|
if (auto s = detail::checked_scratch_bytes(n, kPerVertexBytes, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
|
|
std::vector<std::uint8_t> visited(n, 0);
|
|
std::vector<std::size_t> parent(n, ShortestPathResult::npos);
|
|
std::vector<std::size_t> queue;
|
|
queue.reserve(n);
|
|
|
|
visited[start] = 1;
|
|
queue.push_back(start);
|
|
|
|
bool reached = false;
|
|
std::size_t steps = 0;
|
|
std::size_t head = 0;
|
|
while (head < queue.size() && !reached) {
|
|
const std::size_t u = queue[head++];
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
|
|
for (const auto raw_v : graph.neighbors(u)) {
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
if (!detail::valid_vertex_index(raw_v, n)) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Neighbor vertex index out of range"}};
|
|
}
|
|
const std::size_t v = static_cast<std::size_t>(raw_v);
|
|
if (!visited[v]) {
|
|
visited[v] = 1;
|
|
parent[v] = u;
|
|
queue.push_back(v);
|
|
if (v == target) {
|
|
reached = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
|
|
if (!reached) {
|
|
return ShortestPathResult{
|
|
.found = false,
|
|
.distance = ShortestPathResult::npos,
|
|
.path = {},
|
|
};
|
|
}
|
|
|
|
std::vector<std::size_t> path;
|
|
for (std::size_t cur = target; cur != ShortestPathResult::npos; cur = parent[cur]) {
|
|
path.push_back(cur);
|
|
}
|
|
std::reverse(path.begin(), path.end());
|
|
const std::size_t distance = path.empty() ? 0 : (path.size() - 1);
|
|
return ShortestPathResult{
|
|
.found = true,
|
|
.distance = distance,
|
|
.path = std::move(path),
|
|
};
|
|
}
|
|
|
|
template <IndexedGraphView G>
|
|
[[nodiscard]] std::expected<Topology, AlgorithmError>
|
|
topological_order(const G& graph,
|
|
const WorkLimits& limits = {},
|
|
std::stop_token stop_token = {})
|
|
{
|
|
const auto version = detail::capture_version(graph);
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
|
|
const std::size_t n = static_cast<std::size_t>(graph.vertex_count());
|
|
if (n > limits.max_vertices) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"Vertex count exceeds WorkLimits::max_vertices"}};
|
|
}
|
|
|
|
if (n == 0) {
|
|
return Topology{};
|
|
}
|
|
|
|
constexpr std::size_t kPerVertexBytes = 4 * sizeof(std::size_t);
|
|
const auto base_scratch =
|
|
detail::checked_scratch_bytes(n, kPerVertexBytes, limits);
|
|
if (!base_scratch.has_value()) {
|
|
return std::unexpected{std::move(base_scratch.error())};
|
|
}
|
|
|
|
std::vector<std::size_t> in_degree(n, 0);
|
|
std::size_t steps = 0;
|
|
for (std::size_t u = 0; u < n; ++u) {
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
for (const auto raw_v : graph.neighbors(u)) {
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
if (!detail::valid_vertex_index(raw_v, n)) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Neighbor vertex index out of range"}};
|
|
}
|
|
const std::size_t v = static_cast<std::size_t>(raw_v);
|
|
const auto inc = Void::Numeric::checked_add(in_degree[v], std::size_t{1});
|
|
if (!inc.has_value()) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::overflow,
|
|
"In-degree counter overflowed"}};
|
|
}
|
|
in_degree[v] = *inc;
|
|
}
|
|
}
|
|
|
|
std::vector<std::size_t> queue;
|
|
queue.reserve(n);
|
|
for (std::size_t u = 0; u < n; ++u) {
|
|
if (in_degree[u] == 0) {
|
|
queue.push_back(u);
|
|
}
|
|
}
|
|
|
|
Topology topo;
|
|
topo.order.reserve(n);
|
|
topo.position.assign(n, 0);
|
|
|
|
std::size_t head = 0;
|
|
while (head < queue.size()) {
|
|
const std::size_t u = queue[head++];
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
topo.position[u] = topo.order.size();
|
|
topo.order.push_back(u);
|
|
|
|
for (const auto raw_v : graph.neighbors(u)) {
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
if (!detail::valid_vertex_index(raw_v, n)) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Neighbor vertex index out of range"}};
|
|
}
|
|
const std::size_t v = static_cast<std::size_t>(raw_v);
|
|
if (--in_degree[v] == 0) {
|
|
queue.push_back(v);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (topo.order.size() == n) {
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
return topo;
|
|
}
|
|
|
|
// Extract a deterministic cycle witness [u0, ..., uk, u0] via iterative 3-color DFS.
|
|
enum class Color : std::uint8_t { unvisited = 0, active = 1, done = 2 };
|
|
struct CycleFrame {
|
|
std::size_t vertex;
|
|
std::size_t edge_begin;
|
|
std::size_t edge_end;
|
|
std::size_t edge_cursor;
|
|
};
|
|
|
|
const auto extra_colors = detail::checked_scratch_bytes(n, sizeof(Color), limits);
|
|
if (!extra_colors.has_value() ||
|
|
*base_scratch + *extra_colors > limits.max_scratch_bytes) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"Cycle-witness scratch memory exceeds WorkLimits::max_scratch_bytes"}};
|
|
}
|
|
|
|
std::vector<Color> color(n, Color::unvisited);
|
|
std::vector<CycleFrame> stack;
|
|
std::vector<std::size_t> edge_pool;
|
|
|
|
auto push_frame = [&](std::size_t v) -> std::expected<void, AlgorithmError> {
|
|
color[v] = Color::active;
|
|
const std::size_t begin = edge_pool.size();
|
|
for (const auto raw_nxt : graph.neighbors(v)) {
|
|
if (!detail::valid_vertex_index(raw_nxt, n)) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::invalid_vertex,
|
|
"Neighbor vertex index out of range"}};
|
|
}
|
|
edge_pool.push_back(static_cast<std::size_t>(raw_nxt));
|
|
}
|
|
const std::size_t end = edge_pool.size();
|
|
const std::size_t dyn_bytes =
|
|
(stack.size() + 1) * sizeof(CycleFrame) + edge_pool.size() * sizeof(std::size_t);
|
|
if (*base_scratch + *extra_colors + dyn_bytes > limits.max_scratch_bytes) {
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::limit_exceeded,
|
|
"Cycle-witness scratch memory exceeds WorkLimits::max_scratch_bytes"}};
|
|
}
|
|
stack.push_back(CycleFrame{v, begin, end, begin});
|
|
return {};
|
|
};
|
|
|
|
for (std::size_t seed = 0; seed < n; ++seed) {
|
|
if (in_degree[seed] == 0 || color[seed] != Color::unvisited) {
|
|
continue;
|
|
}
|
|
if (auto p = push_frame(seed); !p.has_value()) {
|
|
return std::unexpected{std::move(p.error())};
|
|
}
|
|
|
|
while (!stack.empty()) {
|
|
if (auto s = detail::step_and_maybe_check(graph, version, stop_token, steps, limits);
|
|
!s.has_value()) {
|
|
return std::unexpected{std::move(s.error())};
|
|
}
|
|
auto& top = stack.back();
|
|
if (top.edge_cursor < top.edge_end) {
|
|
const std::size_t v = edge_pool[top.edge_cursor++];
|
|
if (color[v] == Color::active) {
|
|
std::vector<std::size_t> witness;
|
|
auto it = std::find_if(stack.begin(), stack.end(), [v](const CycleFrame& f) {
|
|
return f.vertex == v;
|
|
});
|
|
for (; it != stack.end(); ++it) {
|
|
witness.push_back(it->vertex);
|
|
}
|
|
witness.push_back(v);
|
|
if (auto c = detail::check_state(graph, version, stop_token); !c.has_value()) {
|
|
return std::unexpected{std::move(c.error())};
|
|
}
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::cycle_detected,
|
|
"Directed graph contains a cycle",
|
|
std::move(witness)}};
|
|
}
|
|
if (color[v] == Color::unvisited) {
|
|
if (auto p = push_frame(v); !p.has_value()) {
|
|
return std::unexpected{std::move(p.error())};
|
|
}
|
|
}
|
|
} else {
|
|
const std::size_t pop_begin = top.edge_begin;
|
|
color[top.vertex] = Color::done;
|
|
stack.pop_back();
|
|
edge_pool.resize(pop_begin);
|
|
}
|
|
}
|
|
}
|
|
|
|
return std::unexpected{AlgorithmError{
|
|
AlgorithmError::Code::cycle_detected,
|
|
"Directed graph contains a cycle"}};
|
|
}
|
|
|
|
} // namespace Void::Algorithms
|