m1une's library

This documentation is automatically generated by online-judge-tools/verification-helper

View on GitHub

:heavy_check_mark: DAG Longest Path
(graph/dag_longest_path.hpp)

Overview

dag_longest_path computes maximum-cost paths from one or more sources in a directed acyclic graph. Edges are relaxed once in topological order, so negative costs are supported and one optimal path can be restored.

The graph must be directed and acyclic. A cyclic graph returns std::nullopt. Inactive edges are ignored.

Requirements

The edge cost type T must be ordered and support construction from 0, addition, and std::numeric_limits<T>::lowest(). The default neg_inf is intended for signed integer or floating-point costs. Pass an explicit sentinel for another compatible type.

Every source starts with distance 0. With multiple sources, the result is the best path beginning at any source, including a zero-edge path. Duplicate source indices have no additional effect.

Result

Member / method Type / signature Meaning Complexity
dist std::vector<T> Maximum distance to each vertex, or neg_inf if unreachable. Access: $O(1)$
parent std::vector<int> Previous vertex on one maximum path, or -1. Access: $O(1)$
parent_edge std::vector<int> Original edge id entering the vertex, or -1. Access: $O(1)$
topological_order std::vector<int> Order used by the relaxation. Access: $O(1)$
neg_inf T Unreachable-distance sentinel. Access: $O(1)$
reachable bool reachable(int v) const Tests whether a source reaches v. $O(1)$
path std::vector<int> path(int t) const Restores one maximum path ending at reachable t. $O(L)$ for path length $L$

Functions

Function Signature Complexity
dag_longest_path template <class T> std::optional<DagLongestPathResult<T>> dag_longest_path(const Graph<T>& g, int s, T neg_inf = std::numeric_limits<T>::lowest() / T(4)) $O(N + M)$ time and $O(N)$ memory
dag_longest_path template <class T> std::optional<DagLongestPathResult<T>> dag_longest_path(const Graph<T>& g, const std::vector<int>& sources, T neg_inf = std::numeric_limits<T>::lowest() / T(4)) $O(N + M)$ time and $O(N)$ memory

Example

#include "graph/dag_longest_path.hpp"
#include "graph/graph.hpp"
#include <iostream>

int main() {
    m1une::graph::Graph<long long> g(4);
    g.add_directed_edge(0, 1, 2);
    g.add_directed_edge(0, 2, 5);
    g.add_directed_edge(1, 3, 7);
    g.add_directed_edge(2, 3, 1);

    auto result = m1une::graph::dag_longest_path(g, 0);
    if (result) std::cout << result->dist[3] << '\n';  // 9
}

Depends on

Required by

Verified with

Code

#ifndef M1UNE_GRAPH_DAG_LONGEST_PATH_HPP
#define M1UNE_GRAPH_DAG_LONGEST_PATH_HPP 1

#include <algorithm>
#include <cassert>
#include <limits>
#include <optional>
#include <vector>

#include "graph.hpp"
#include "topological_sort.hpp"

namespace m1une {
namespace graph {

template <class T>
struct DagLongestPathResult {
    std::vector<T> dist;
    std::vector<int> parent;
    std::vector<int> parent_edge;
    std::vector<int> topological_order;
    T neg_inf;

    bool reachable(int v) const {
        assert(0 <= v && v < int(dist.size()));
        return dist[v] != neg_inf;
    }

    std::vector<int> path(int t) const {
        assert(reachable(t));
        std::vector<int> result;
        for (int v = t; v != -1; v = parent[v]) result.push_back(v);
        std::reverse(result.begin(), result.end());
        return result;
    }
};

template <class T>
std::optional<DagLongestPathResult<T>> dag_longest_path(
    const Graph<T>& g,
    const std::vector<int>& sources,
    T neg_inf = std::numeric_limits<T>::lowest() / T(4)
) {
    const int n = g.size();
    auto order = topological_sort(g);
    if (!order) return std::nullopt;

    DagLongestPathResult<T> result;
    result.dist.assign(n, neg_inf);
    result.parent.assign(n, -1);
    result.parent_edge.assign(n, -1);
    result.topological_order = *order;
    result.neg_inf = neg_inf;

    for (int s : sources) {
        assert(0 <= s && s < n);
        result.dist[s] = T(0);
    }

    for (int v : *order) {
        if (result.dist[v] == neg_inf) continue;
        for (const auto& e : g[v]) {
            if (!e.alive) continue;
            T nd = result.dist[v] + e.cost;
            if (result.dist[e.to] >= nd) continue;
            result.dist[e.to] = nd;
            result.parent[e.to] = v;
            result.parent_edge[e.to] = e.id;
        }
    }

    return result;
}

template <class T>
std::optional<DagLongestPathResult<T>> dag_longest_path(
    const Graph<T>& g,
    int s,
    T neg_inf = std::numeric_limits<T>::lowest() / T(4)
) {
    return dag_longest_path(g, std::vector<int>{s}, neg_inf);
}

}  // namespace graph
}  // namespace m1une

#endif  // M1UNE_GRAPH_DAG_LONGEST_PATH_HPP
#line 1 "graph/dag_longest_path.hpp"



#include <algorithm>
#include <cassert>
#include <limits>
#include <optional>
#include <vector>

#line 1 "graph/graph.hpp"



#include <array>
#line 6 "graph/graph.hpp"
#include <utility>
#line 8 "graph/graph.hpp"

namespace m1une {
namespace graph {

template <class T = int>
struct Edge {
    using cost_type = T;

    int from;
    int to;
    T cost;
    int id;
    bool alive;

    Edge() : from(-1), to(-1), cost(T()), id(-1), alive(true) {}
    Edge(int from_, int to_, T cost_ = T(1), int id_ = -1, bool alive_ = true)
        : from(from_), to(to_), cost(cost_), id(id_), alive(alive_) {}

    int other(int v) const {
        assert(v == from || v == to);
        return from ^ to ^ v;
    }
};

template <class T = int>
struct Graph {
    using edge_type = Edge<T>;
    using cost_type = T;

   private:
    struct EdgePositions {
        std::array<std::pair<int, int>, 2> value{};
        int size = 0;

        void push_back(std::pair<int, int> position) {
            assert(size < 2);
            value[size++] = position;
        }
    };

    int _n;
    int _edge_count;
    std::vector<std::vector<edge_type>> _g;
    std::vector<EdgePositions> _edge_positions;

   public:
    Graph() : _n(0), _edge_count(0) {}
    explicit Graph(int n) : _n(n), _edge_count(0), _g(n) {
        assert(0 <= n);
    }

    int size() const {
        return _n;
    }

    bool empty() const {
        return _n == 0;
    }

    int edge_count() const {
        return _edge_count;
    }

    int add_vertex() {
        _g.emplace_back();
        return _n++;
    }

    int add_directed_edge(int from, int to, T cost = T(1)) {
        assert(0 <= from && from < _n);
        assert(0 <= to && to < _n);
        int id = _edge_count++;
        int idx = int(_g[from].size());
        _g[from].push_back(edge_type(from, to, cost, id));
        _edge_positions.emplace_back();
        _edge_positions.back().push_back({from, idx});
        return id;
    }

    int add_edge(int u, int v, T cost = T(1)) {
        assert(0 <= u && u < _n);
        assert(0 <= v && v < _n);
        int id = _edge_count++;
        int u_idx = int(_g[u].size());
        _g[u].push_back(edge_type(u, v, cost, id));
        int v_idx = int(_g[v].size());
        _g[v].push_back(edge_type(v, u, cost, id));
        _edge_positions.emplace_back();
        _edge_positions.back().push_back({u, u_idx});
        _edge_positions.back().push_back({v, v_idx});
        return id;
    }

    void set_edge_alive(int id, bool alive) {
        assert(0 <= id && id < _edge_count);
        for (int i = 0; i < _edge_positions[id].size; ++i) {
            auto [v, idx] = _edge_positions[id].value[i];
            _g[v][idx].alive = alive;
        }
    }

    void erase_edge(int id) {
        set_edge_alive(id, false);
    }

    void revive_edge(int id) {
        set_edge_alive(id, true);
    }

    bool is_edge_alive(int id) const {
        assert(0 <= id && id < _edge_count);
        assert(_edge_positions[id].size != 0);
        auto [v, idx] = _edge_positions[id].value[0];
        return _g[v][idx].alive;
    }

    const std::vector<edge_type>& operator[](int v) const {
        assert(0 <= v && v < _n);
        return _g[v];
    }

    std::vector<edge_type>& operator[](int v) {
        assert(0 <= v && v < _n);
        return _g[v];
    }

    const std::vector<std::vector<edge_type>>& adjacency() const {
        return _g;
    }

    std::vector<std::vector<edge_type>>& adjacency() {
        return _g;
    }

    std::vector<edge_type> edges(bool include_inactive = false) const {
        std::vector<edge_type> result;
        result.reserve(_edge_count);
        std::vector<char> used(_edge_count, false);
        for (int v = 0; v < _n; v++) {
            for (const auto& e : _g[v]) {
                if (!include_inactive && !e.alive) continue;
                if (0 <= e.id && e.id < _edge_count) {
                    if (used[e.id]) continue;
                    used[e.id] = true;
                }
                result.push_back(e);
            }
        }
        return result;
    }

    Graph reversed() const {
        Graph result(_n);
        result._edge_count = _edge_count;
        result._edge_positions.assign(_edge_count, {});
        for (int v = 0; v < _n; v++) {
            for (const auto& e : _g[v]) {
                int idx = int(result._g[e.to].size());
                result._g[e.to].push_back(edge_type(e.to, e.from, e.cost, e.id, e.alive));
                if (0 <= e.id && e.id < _edge_count) result._edge_positions[e.id].push_back({e.to, idx});
            }
        }
        return result;
    }
};

}  // namespace graph
}  // namespace m1une


#line 1 "graph/topological_sort.hpp"



#line 5 "graph/topological_sort.hpp"
#include <queue>
#line 7 "graph/topological_sort.hpp"

#line 9 "graph/topological_sort.hpp"

namespace m1une {
namespace graph {

template <class T>
std::optional<std::vector<int>> topological_sort(const Graph<T>& g) {
    int n = g.size();
    std::vector<int> indeg(n, 0);
    for (int v = 0; v < n; v++) {
        for (const auto& e : g[v]) {
            if (!e.alive) continue;
            indeg[e.to]++;
        }
    }

    std::queue<int> que;
    for (int v = 0; v < n; v++) {
        if (indeg[v] == 0) que.push(v);
    }

    std::vector<int> order;
    order.reserve(n);
    while (!que.empty()) {
        int v = que.front();
        que.pop();
        order.push_back(v);
        for (const auto& e : g[v]) {
            if (!e.alive) continue;
            indeg[e.to]--;
            if (indeg[e.to] == 0) que.push(e.to);
        }
    }

    if (int(order.size()) != n) return std::nullopt;
    return order;
}

template <class T>
bool is_dag(const Graph<T>& g) {
    return topological_sort(g).has_value();
}

}  // namespace graph
}  // namespace m1une


#line 12 "graph/dag_longest_path.hpp"

namespace m1une {
namespace graph {

template <class T>
struct DagLongestPathResult {
    std::vector<T> dist;
    std::vector<int> parent;
    std::vector<int> parent_edge;
    std::vector<int> topological_order;
    T neg_inf;

    bool reachable(int v) const {
        assert(0 <= v && v < int(dist.size()));
        return dist[v] != neg_inf;
    }

    std::vector<int> path(int t) const {
        assert(reachable(t));
        std::vector<int> result;
        for (int v = t; v != -1; v = parent[v]) result.push_back(v);
        std::reverse(result.begin(), result.end());
        return result;
    }
};

template <class T>
std::optional<DagLongestPathResult<T>> dag_longest_path(
    const Graph<T>& g,
    const std::vector<int>& sources,
    T neg_inf = std::numeric_limits<T>::lowest() / T(4)
) {
    const int n = g.size();
    auto order = topological_sort(g);
    if (!order) return std::nullopt;

    DagLongestPathResult<T> result;
    result.dist.assign(n, neg_inf);
    result.parent.assign(n, -1);
    result.parent_edge.assign(n, -1);
    result.topological_order = *order;
    result.neg_inf = neg_inf;

    for (int s : sources) {
        assert(0 <= s && s < n);
        result.dist[s] = T(0);
    }

    for (int v : *order) {
        if (result.dist[v] == neg_inf) continue;
        for (const auto& e : g[v]) {
            if (!e.alive) continue;
            T nd = result.dist[v] + e.cost;
            if (result.dist[e.to] >= nd) continue;
            result.dist[e.to] = nd;
            result.parent[e.to] = v;
            result.parent_edge[e.to] = e.id;
        }
    }

    return result;
}

template <class T>
std::optional<DagLongestPathResult<T>> dag_longest_path(
    const Graph<T>& g,
    int s,
    T neg_inf = std::numeric_limits<T>::lowest() / T(4)
) {
    return dag_longest_path(g, std::vector<int>{s}, neg_inf);
}

}  // namespace graph
}  // namespace m1une
Back to top page