sirkit-cpp-library

競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。

View the Project on GitHub reinsirk/sirkit-cpp-library

関数グラフの経路積

Graph/Functional_Graph_Fold.cpp · ソース · 文書 Last Commit

通常版・コンパイラ共通 · この版の一覧へ

通常版・GCC専用 · この版の一覧へ

通常版・Clang専用 · この版の一覧へ

通常版・MSVC専用 · この版の一覧へ

速度優先版・コンパイラ共通 · この版の一覧へ

速度優先版・GCC専用 · この版の一覧へ

速度優先版・Clang専用 · この版の一覧へ

速度優先版・MSVC専用 · この版の一覧へ

各頂点から出る辺が1本のグラフで、指定回数だけ進んだ頂点と、通った辺のラベルの積を求めます。和や最大値に加えて、文字列の連結や関数合成など順序がある演算にも使えます。本体

FunctionalGraphFold<T, Combine>(next, label, identity, combine = {});
walk(v, k) -> std::pair<int, T>;
size() -> int;
  • next[v] が頂点 v の行き先、label[v] がその辺のラベルです。頂点番号は $0$ 始まりです。
  • combine(a, b) は先に通った区間の値 a と次の区間の値 b をこの順に結合します。結合則を満たし、identity は両側の単位元とします。既定の演算は std::plus<T> です。
  • walk(v, k) は進んだ先と積を返します。回数 k は std::uint64_t で、$0$ 回なら {v, identity} を返します。
  • size() は頂点数を返します。

演算と値のコピーを $O(1)$ とすると、前処理と領域は $O(n\log(n+1))$、walk は $O(\log(n+1)+\log(k+1))$ です。周期を何周もする場合は、1周分の積を繰り返し二乗法でまとめます。

使用例

const std::array next{1, 2, 1};
const std::array<std::uint64_t, 3> label{10, 2, 5};
const sirkit::FunctionalGraphFold<std::uint64_t> walk(next, label, 0);
const auto [v, sum] = walk.walk(0, 5);  // v == 1, sum == 24

使用例・和のVerify・最大接頭辞和のVerify

ソースのAPI注記
FunctionalGraphFold<T, Combine>(next, label, identity, combine={}):
  頂点vからnext[v]へ進む辺にlabel[v]を置く。combineは結合的でidentityは両側単位元。
  前処理と領域はO(n log(n+1))。積と値のコピーをO(1)とする。
walk(v, k): k本の辺を進んだ頂点と、通った辺ラベルの順序付き積を返す。
  kはuint64_t。0本では{v, identity}。O(log(n+1)+log(k+1))。
size(): 頂点数。O(1)。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Putting Candies functional_graph_fold.cpp 未提出 —
Moving Piece functional_graph_fold_max_prefix.cpp 未提出 —

✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。

ローカル・CI検査

検査 状態
正常系 未実施
失敗系 未測定
Library Checker公式ケース 無し
性能測定 未実施
ASan/UBSan 未実施
カバレッジ 未実施

到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。

実行条件・件数・測定結果 · 結果JSON

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/functional_graph_fold.md
//
// API一覧
// FunctionalGraphFold<T, Combine>(next, label, identity, combine={}):
//   頂点vからnext[v]へ進む辺にlabel[v]を置く。combineは結合的でidentityは両側単位元。
//   前処理と領域はO(n log(n+1))。積と値のコピーをO(1)とする。
// walk(v, k): k本の辺を進んだ頂点と、通った辺ラベルの順序付き積を返す。
//   kはuint64_t。0本では{v, identity}。O(log(n+1)+log(k+1))。
// size(): 頂点数。O(1)。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <bit>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
#include <span>
#include <stdexcept>
#include <utility>
#include <vector>


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_FUNCTIONAL_GRAPH_FOLD_DEFINED
#define SIRKIT_FUNCTIONAL_GRAPH_FOLD_DEFINED

namespace detail
{
inline int functional_graph_fold_vertex_count(std::size_t n)
{
    if (n > static_cast<std::size_t>(std::numeric_limits<int>::max()))
    {
        throw std::length_error("FunctionalGraphFold: too many vertices");
    }
    return static_cast<int>(n);
}
} // namespace detail

template <class T, class Combine = std::plus<T>>
class FunctionalGraphFold
{
    struct Jump
    {
        int end;
        T product;
    };

public:
    FunctionalGraphFold(std::span<const int> next, std::span<const T> label, T identity, Combine combine = {})
        : identity_(std::move(identity)), combine_(std::move(combine))
    {
        const int n = detail::functional_graph_fold_vertex_count(next.size());
        if (next.size() != label.size())
        {
            throw std::invalid_argument("FunctionalGraphFold: inconsistent label count");
        }
        build_periods(next, n);
        const unsigned levels = std::bit_width(static_cast<unsigned>(n));
        jumps_.reserve(next.size() * levels);
        for (int v = 0; v < n; ++v)
        {
            jumps_.push_back({next[v], label[v]});
        }
        for (unsigned level = 1; level < levels; ++level)
        {
            const std::size_t base = static_cast<std::size_t>(n) * (level - 1);
            for (int v = 0; v < n; ++v)
            {
                const auto &first = jumps_[base + v];
                const auto &second = jumps_[base + first.end];
                jumps_.push_back({second.end, combine_(first.product, second.product)});
            }
        }
    }

    [[nodiscard]] int size() const noexcept
    {
        return static_cast<int>(depth_.size());
    }

    [[nodiscard]] std::pair<int, T> walk(int from, std::uint64_t steps) const
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (from < 0 || from >= size())
        {
            throw std::out_of_range("FunctionalGraphFold: invalid start vertex");
        }
#endif
        T product = identity_;
        if (steps <= depth_.size())
        {
            append(from, steps, product);
            return {from, std::move(product)};
        }

        const auto tail = static_cast<std::uint64_t>(depth_[from]);
        append(from, tail, product);
        steps -= tail;
        const auto period = static_cast<std::uint64_t>(period_[from]);
        T cycle = identity_;
        append(from, period, cycle);
        for (std::uint64_t copies = steps / period; copies != 0;)
        {
            if (copies & 1)
            {
                product = combine_(product, cycle);
            }
            copies >>= 1;
            if (copies != 0)
            {
                cycle = combine_(cycle, cycle);
            }
        }
        append(from, steps % period, product);
        return {from, std::move(product)};
    }

private:
    void build_periods(std::span<const int> next, int n)
    {
        std::vector<int> indegree(n);
        for (const int v : next)
        {
#ifndef SKIP_RUNTIME_CHECKS
            if (v < 0 || v >= n)
            {
                throw std::out_of_range("FunctionalGraphFold: invalid destination");
            }
#endif
            ++indegree[v];
        }
        std::vector<int> peeled;
        peeled.reserve(n);
        for (int v = 0; v < n; ++v)
        {
            if (indegree[v] == 0)
            {
                peeled.push_back(v);
            }
        }
        for (std::size_t i = 0; i < peeled.size(); ++i)
        {
            const int to = next[peeled[i]];
            if (--indegree[to] == 0)
            {
                peeled.push_back(to);
            }
        }

        depth_.resize(n);
        period_.resize(n);
        for (int start = 0; start < n; ++start)
        {
            if (indegree[start] != 0 && period_[start] == 0)
            {
                int length = 1;
                for (int v = next[start]; v != start; v = next[v])
                {
                    ++length;
                }
                int v = start;
                do
                {
                    period_[v] = length;
                    v = next[v];
                } while (v != start);
            }
        }
        for (auto it = peeled.rbegin(); it != peeled.rend(); ++it)
        {
            const int v = *it;
            depth_[v] = depth_[next[v]] + 1;
            period_[v] = period_[next[v]];
        }
    }

    void append(int &from, std::uint64_t steps, T &product) const
    {
        while (steps != 0)
        {
            const auto level = std::countr_zero(steps);
            const auto &jump = jumps_[depth_.size() * level + from];
            product = combine_(product, jump.product);
            from = jump.end;
            steps &= steps - 1;
        }
    }

    T identity_;
    [[no_unique_address]] Combine combine_;
    std::vector<int> depth_;
    std::vector<int> period_;
    std::vector<Jump> jumps_;
};

#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1
Back to top page