m1une's library

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

View on GitHub

:heavy_check_mark: DAG Path Count
(graph/dag_path_count.hpp)

Overview

dag_path_count counts directed paths from one or more sources to every vertex of a DAG. It is useful for dependency counting and standard DAG dynamic programming.

Each source contributes one zero-edge path to itself. Parallel active edges describe distinct paths, inactive edges are ignored, and duplicate source indices are counted once. A cyclic graph returns std::nullopt.

Count defaults to long long. It only needs construction from 0 and 1 and addition, so a modular integer type can be supplied when counts are large. Overflow follows the behavior of Count.

Functions

Function Signature Description Complexity
dag_path_count template <class Count = long long, class T> std::optional<std::vector<Count>> dag_path_count(const Graph<T>& g, int s) Counts paths beginning at s. $O(N + M)$ time and $O(N)$ memory
dag_path_count template <class Count = long long, class T> std::optional<std::vector<Count>> dag_path_count(const Graph<T>& g, const std::vector<int>& sources) Counts paths beginning at any source. $O(N + M)$ time and $O(N)$ memory

Example

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

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

    auto ways = m1une::graph::dag_path_count(g, 0);
    if (ways) std::cout << (*ways)[3] << '\n';  // 2
}

Depends on

Required by

Verified with

Code

#ifndef M1UNE_GRAPH_DAG_PATH_COUNT_HPP
#define M1UNE_GRAPH_DAG_PATH_COUNT_HPP 1

#include <cassert>
#include <optional>
#include <vector>

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

namespace m1une {
namespace graph {

template <class Count = long long, class T>
std::optional<std::vector<Count>> dag_path_count(
    const Graph<T>& g,
    const std::vector<int>& sources
) {
    const int n = g.size();
    auto order = topological_sort(g);
    if (!order) return std::nullopt;

    std::vector<Count> ways(n, Count(0));
    std::vector<char> used_source(n, false);
    for (int s : sources) {
        assert(0 <= s && s < n);
        if (used_source[s]) continue;
        used_source[s] = true;
        ways[s] += Count(1);
    }

    for (int v : *order) {
        for (const auto& e : g[v]) {
            if (e.alive) ways[e.to] += ways[v];
        }
    }
    return ways;
}

template <class Count = long long, class T>
std::optional<std::vector<Count>> dag_path_count(const Graph<T>& g, int s) {
    return dag_path_count<Count>(g, std::vector<int>{s});
}

}  // namespace graph
}  // namespace m1une

#endif  // M1UNE_GRAPH_DAG_PATH_COUNT_HPP
#line 1 "graph/dag_path_count.hpp"



#include <cassert>
#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 10 "graph/dag_path_count.hpp"

namespace m1une {
namespace graph {

template <class Count = long long, class T>
std::optional<std::vector<Count>> dag_path_count(
    const Graph<T>& g,
    const std::vector<int>& sources
) {
    const int n = g.size();
    auto order = topological_sort(g);
    if (!order) return std::nullopt;

    std::vector<Count> ways(n, Count(0));
    std::vector<char> used_source(n, false);
    for (int s : sources) {
        assert(0 <= s && s < n);
        if (used_source[s]) continue;
        used_source[s] = true;
        ways[s] += Count(1);
    }

    for (int v : *order) {
        for (const auto& e : g[v]) {
            if (e.alive) ways[e.to] += ways[v];
        }
    }
    return ways;
}

template <class Count = long long, class T>
std::optional<std::vector<Count>> dag_path_count(const Graph<T>& g, int s) {
    return dag_path_count<Count>(g, std::vector<int>{s});
}

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