sirkit-cpp-library

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

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

Stern–Brocot 木

Math/Stern_Brocot_Tree.cpp · ソース · 文書 現行ACあり Last Commit

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

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

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

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

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

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

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

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

すべての正の有理数が1回ずつ現れる二分探索木です。根は 1/1、左の子へ進むと値は小さく、右の子へ進むと大きくなります。同じ向きに続く移動をまとめて扱います。

using Tree = sirkit::SternBrocotTree;
const auto path = Tree::encode({5, 3}); // {{'R', 1}, {'L', 1}, {'R', 1}}
assert((Tree::decode(path) == Tree::Fraction{5, 3}));

Fraction は std::uint64_t の {分子, 分母} です。入力の分子・分母は正とし、約分済みでなくても構いません。戻り値は既約です。Run は {方向, 回数} で、方向は 'L' または 'R'、回数は正の std::uint64_t です。扱う Run の数を R とすると、全操作が O(R+1) 時間で、出力以外に O(1) 領域を使います。分数からたどる Run の数は分子と分母の大きい方に対して対数です。

encode

static std::vector<Run> encode(Fraction fraction);

根から指定した分数までのパスを、同じ方向が続く区間ごとにまとめて返します。根のパスは空です。

decode

static Fraction decode(std::span<const Run> path);

根からパスをたどった分数を返します。分子または分母が std::uint64_t に収まらなければ、std::overflow_error を送出します。

ancestor

static std::optional<Fraction> ancestor(Fraction fraction, std::uint64_t depth);

根を深さ0とし、指定した深さの祖先を返します。深さが分数自身より大きければ std::nullopt を返します。

lca

static Fraction lca(Fraction a, Fraction b);

2つの分数の共通祖先のうち、最も深いものを返します。

approximate

static std::pair<Fraction, Fraction> approximate(Fraction fraction,
    std::uint64_t max_numerator, std::uint64_t max_denominator);

分子・分母がそれぞれ上限以下の数のうち、fraction 以下の最大値と fraction 以上の最小値を返します。fraction の既約形が両方の上限に収まる場合、両端が同じ分数になります。下側に候補がないときは {0, 1}、上側に候補がないときは {1, 0} です。上限のどちらかが0なら両側に候補がありません。

range

static std::pair<Fraction, Fraction> range(Fraction fraction);

指定した分数を根とする部分木に含まれる値の開区間を {下限, 上限} で返します。下限の0は {0, 1}、上限の正の無限大は {1, 0} です。

使用例 / 木操作のVerify / 近似のVerify / Nyaan の関連実装

ソースのAPI注記
[SternBrocotTree]
Fraction: uint64_tの{分子,分母}。正の分数を受け取り、既約分数を返す。
Run: {方向,回数}。方向は'L'か'R'、回数は正。長さ0のパスは根1/1。
encode(f): 連長圧縮した根からfへのパス。decode(path): パスから分数。
ancestor(f,depth): 深さdepthの祖先。根は深さ0。深すぎる場合はnullopt。
lca(a,b): a,bの最小共通祖先。range(f): f以下の部分木が表す開区間。
approximate(f,max_numerator,max_denominator): 分子・分母が上限以下の最近接の下側・上側の分数。
範囲や近似に有限な端点がなければ0/1または1/0。
時間は扱うラン数Rに対してO(R+1)。分数からのラン数はO(log(max(分子,分母)+1))。
encodeの出力以外の追加領域はO(1)。
decodeは結果がuint64_tに収まらない場合にstd::overflow_error。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Rational Approximation rational_approximation.cpp ✓ 現行AC AC
Stern–Brocot Tree stern_brocot_tree.cpp ✓ 現行AC AC

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

ローカル・CI検査

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

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

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

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// 参考: https://nyaannyaan.github.io/library/math/stern-brocot-tree-binary-search.hpp
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/stern_brocot_tree.md
//
// API一覧
// [SternBrocotTree]
// Fraction: uint64_tの{分子,分母}。正の分数を受け取り、既約分数を返す。
// Run: {方向,回数}。方向は'L'か'R'、回数は正。長さ0のパスは根1/1。
// encode(f): 連長圧縮した根からfへのパス。decode(path): パスから分数。
// ancestor(f,depth): 深さdepthの祖先。根は深さ0。深すぎる場合はnullopt。
// lca(a,b): a,bの最小共通祖先。range(f): f以下の部分木が表す開区間。
// approximate(f,max_numerator,max_denominator): 分子・分母が上限以下の最近接の下側・上側の分数。
// 範囲や近似に有限な端点がなければ0/1または1/0。
// 時間は扱うラン数Rに対してO(R+1)。分数からのラン数はO(log(max(分子,分母)+1))。
// encodeの出力以外の追加領域はO(1)。
// decodeは結果がuint64_tに収まらない場合にstd::overflow_error。

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

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

class SternBrocotTree
{
public:
    using Fraction = std::pair<std::uint64_t, std::uint64_t>;
    using Run = std::pair<char, std::uint64_t>;

private:
    struct Interval
    {
        Fraction lower{0, 1};
        Fraction upper{1, 0};
    };

    static std::uint64_t AddScaled(std::uint64_t value, std::uint64_t other, std::uint64_t count)
    {
        if (other != 0 && count > (std::numeric_limits<std::uint64_t>::max() - value) / other)
        {
            throw std::overflow_error("SternBrocotTree: fraction");
        }
        return value + other * count;
    }

    static void Move(Interval &interval, char direction, std::uint64_t count)
    {
        auto &[a, b] = direction == 'L' ? interval.upper : interval.lower;
        const auto [c, d] = direction == 'L' ? interval.lower : interval.upper;
        a = AddScaled(a, c, count);
        b = AddScaled(b, d, count);
    }

    static Fraction Mediant(const Interval &interval)
    {
        const auto [a, b] = interval.lower;
        const auto [c, d] = interval.upper;
        return {AddScaled(a, c, 1), AddScaled(b, d, 1)};
    }

    static void CheckFraction([[maybe_unused]] Fraction fraction)
    {
#ifndef SKIP_RUNTIME_CHECKS
        if (fraction.first == 0 || fraction.second == 0)
        {
            throw std::invalid_argument("SternBrocotTree: positive fraction required");
        }
#endif
    }

    static Run TakeRun(Fraction &fraction)
    {
        auto &[a, b] = fraction;
        if (a < b)
        {
            const auto count = (b - 1) / a;
            b -= count * a;
            return {'L', count};
        }
        const auto count = (a - 1) / b;
        a -= count * b;
        return {'R', count};
    }

public:
    static std::vector<Run> encode(Fraction fraction)
    {
        CheckFraction(fraction);
        std::vector<Run> path;
        while (fraction.first != fraction.second)
        {
            path.push_back(TakeRun(fraction));
        }
        return path;
    }

    static Fraction decode(std::span<const Run> path)
    {
        Interval interval;
        for (const auto &[direction, count] : path)
        {
#ifndef SKIP_RUNTIME_CHECKS
            if ((direction != 'L' && direction != 'R') || count == 0)
            {
                throw std::invalid_argument("SternBrocotTree: invalid path");
            }
#endif
            Move(interval, direction, count);
        }
        return Mediant(interval);
    }

    static std::optional<Fraction> ancestor(Fraction fraction, std::uint64_t depth)
    {
        CheckFraction(fraction);
        Interval interval;
        while (depth != 0 && fraction.first != fraction.second)
        {
            const auto [direction, count] = TakeRun(fraction);
            const auto steps = std::min(depth, count);
            Move(interval, direction, steps);
            depth -= steps;
        }
        if (depth != 0)
        {
            return std::nullopt;
        }
        return Mediant(interval);
    }

    static Fraction lca(Fraction a, Fraction b)
    {
        CheckFraction(a);
        CheckFraction(b);
        Interval interval;
        while (a.first != a.second && b.first != b.second)
        {
            const auto [left_direction, left_count] = TakeRun(a);
            const auto [right_direction, right_count] = TakeRun(b);
            if (left_direction != right_direction)
            {
                break;
            }
            Move(interval, left_direction, std::min(left_count, right_count));
            if (left_count != right_count)
            {
                break;
            }
        }
        return Mediant(interval);
    }

    static std::pair<Fraction, Fraction> approximate(Fraction fraction, std::uint64_t max_numerator, std::uint64_t max_denominator)
    {
        CheckFraction(fraction);
        Interval interval;
        if (max_numerator == 0 || max_denominator == 0)
        {
            return {interval.lower, interval.upper};
        }
        while (interval.lower.first <= max_numerator - interval.upper.first &&
               interval.lower.second <= max_denominator - interval.upper.second)
        {
            if (fraction.first == fraction.second)
            {
                const auto exact = Mediant(interval);
                return {exact, exact};
            }
            const auto [direction, count] = TakeRun(fraction);
            const auto &[a, b] = direction == 'L' ? interval.upper : interval.lower;
            const auto &[c, d] = direction == 'L' ? interval.lower : interval.upper;
            auto steps = count;
            if (c != 0)
            {
                steps = std::min(steps, (max_numerator - a) / c);
            }
            if (d != 0)
            {
                steps = std::min(steps, (max_denominator - b) / d);
            }
            Move(interval, direction, steps);
        }
        return {interval.lower, interval.upper};
    }

    static std::pair<Fraction, Fraction> range(Fraction fraction)
    {
        CheckFraction(fraction);
        Interval interval;
        while (fraction.first != fraction.second)
        {
            const auto [direction, count] = TakeRun(fraction);
            Move(interval, direction, count);
        }
        return {interval.lower, interval.upper};
    }
};

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