Library

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

View the Project on GitHub ebi-fly13/Library

:heavy_check_mark: test/math/Stern-Brocot_Tree.test.cpp

Depends on

Code

#define PROBLEM "https://judge.yosupo.jp/problem/stern_brocot_tree"

#include "../../math/stern_brocot_tree.hpp"
#include "../../template/template.hpp"

namespace ebi {

void main_() {
    std::string type;
    std::cin >> type;
    if (type == "ENCODE_PATH") {
        i64 a, b;
        std::cin >> a >> b;
        auto path = stern_brocot_tree::encode_path({a, b});
        stern_brocot_tree::print_path(path);
    } else if (type == "DECODE_PATH") {
        int k;
        std::cin >> k;
        std::vector<std::pair<char, i64>> path(k);
        for (auto &[c, n] : path) {
            std::cin >> c >> n;
        }
        auto lr = stern_brocot_tree::decode_path(path);
        auto f = stern_brocot_tree::val(lr);
        std::cout << f << '\n';
    } else if (type == "LCA") {
        i64 a, b, c, d;
        std::cin >> a >> b >> c >> d;
        std::cout << stern_brocot_tree::lca({a, b}, {c, d}) << '\n';
    } else if (type == "ANCESTOR") {
        i64 k, a, b;
        std::cin >> k >> a >> b;
        auto f = stern_brocot_tree::ancestor(k, {a, b});
        if (f) {
            std::cout << f.value() << '\n';
        } else {
            std::cout << "-1\n";
        }
    } else if (type == "RANGE") {
        i64 a, b;
        std::cin >> a >> b;
        std::cout << stern_brocot_tree::range({a, b}) << '\n';
    }
}

}  // namespace ebi

int main() {
    ebi::fast_io();
    int t = 1;
    std::cin >> t;
    while (t--) {
        ebi::main_();
    }
    return 0;
}
#line 1 "test/math/Stern-Brocot_Tree.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/stern_brocot_tree"

#line 2 "math/stern_brocot_tree.hpp"

#include <algorithm>
#include <cassert>
#include <concepts>
#include <cstdint>
#include <iostream>
#include <optional>
#include <vector>

/*
reference: https://miscalc.hatenablog.com/entry/2023/12/22/213007
           https://rsk0315.hatenablog.com/entry/2023/04/17/022705
           https://atcoder.jp/contests/abc294/editorial/6017
*/

namespace ebi {

struct stern_brocot_tree {
  private:
    using value_type = std::int64_t;
    using T = value_type;
    using Fraction = std::pair<T, T>;

    static Fraction add(const Fraction &lhs, const Fraction &rhs) {
        return {lhs.first + rhs.first, lhs.second + rhs.second};
    }

    static Fraction mul(const T k, const Fraction &a) {
        return {k * a.first, k * a.second};
    }

    static bool compare(Fraction a, Fraction b) {
        return __int128_t(a.first) * b.second < __int128_t(a.second) * b.first;
    }

    static void euler_tour_order(std::vector<Fraction> &fs) {
        std::sort(fs.begin(), fs.end(), [&](Fraction a, Fraction b) -> bool {
            if (a == b) return false;
            if (in_subtree(a, b)) return false;
            if (in_subtree(b, a)) return true;
            return compare(a, b);
        });
    }

  public:
    stern_brocot_tree() = default;

    static std::vector<T> encode_path(const Fraction &f) {
        auto [x, y] = f;
        std::vector<T> path;
        while (x != y) {
            T m = (x - 1) / y;
            path.emplace_back(m);
            x -= m * y;
            std::swap(x, y);
        }
        return path;
    }

    static std::pair<Fraction, Fraction> decode_path(
        const std::vector<T> &path) {
        T lx = 0, ly = 1, rx = 1, ry = 0;
        for (bool is_right = true; auto n : path) {
            if (is_right) {
                lx += rx * n;
                ly += ry * n;
            } else {
                rx += lx * n;
                ry += ly * n;
            }
            is_right = !is_right;
        }
        return {{lx, ly}, {rx, ry}};
    }

    static std::pair<Fraction, Fraction> decode_path(
        const std::vector<std::pair<char, T>> &path) {
        if (path.empty()) {
            return {{0, 1}, {1, 0}};
        }
        std::vector<T> p;
        bool is_right = true;
        if (path[0].first == 'L') {
            p.emplace_back(0);
            is_right = !is_right;
        }
        for (auto [c, n] : path) {
            assert(c == (is_right ? 'R' : 'L'));
            p.emplace_back(n);
            is_right = !is_right;
        }
        return decode_path(p);
    }

    static Fraction lca(Fraction f, Fraction g) {
        auto path_f = encode_path(f);
        auto path_g = encode_path(g);
        std::vector<T> path_h;
        for (int i = 0; i < (int)std::min(path_f.size(), path_g.size()); i++) {
            T k = std::min(path_f[i], path_g[i]);
            path_h.emplace_back(k);
            if (path_f[i] != path_g[i]) {
                break;
            }
        }
        return val(decode_path(path_h));
    }

    static std::optional<Fraction> ancestor(T k, Fraction f) {
        std::vector<T> path;
        for (auto n : encode_path(f)) {
            T m = std::min(k, n);
            path.emplace_back(m);
            k -= m;
            if (k == 0) break;
        }
        if (k > 0) return std::nullopt;
        return val(decode_path(path));
    }

    static std::pair<Fraction, Fraction> range(Fraction f) {
        return decode_path(encode_path(f));
    }

    template <class F> static Fraction binary_search(const T max_value, F f) {
        Fraction l = {0, 1}, r = {1, 0};
        while (true) {
            Fraction now = val({l, r});
            bool flag = f(now);
            Fraction from = flag ? l : r;
            Fraction to = flag ? r : l;
            T ok = 1, ng = 2;
            while (f(add(from, mul(ng, to))) == flag) {
                ok <<= 1;
                ng <<= 1;
                auto nxt = add(from, mul(ok, to));
                if (nxt.first > max_value || nxt.second > max_value) return to;
            }
            while (ng - ok > 1) {
                T mid = (ok + ng) >> 1;
                if (f(add(from, mul(mid, to))) == flag) {
                    ok = mid;
                } else {
                    ng = mid;
                }
            }
            (flag ? l : r) = add(from, mul(ok, to));
        }
        assert(0);
        return l;
    }

    static std::pair<Fraction, Fraction> nearest_fraction(T max, Fraction f) {
        Fraction l = {0, 1}, r = {1, 0};
        for (bool is_right = true; auto n : encode_path(f)) {
            Fraction nl = l, nr = r;
            if (is_right) {
                nl = add(l, mul(n, r));
            } else {
                nr = add(r, mul(n, l));
            }
            if (std::max(nl.second, nr.second) > max) {
                nl = l, nr = r;
                if (is_right) {
                    T x = (max - l.second) / r.second;
                    nl.first += r.first * x;
                    nl.second += r.second * x;
                } else {
                    T x = (max - r.second) / l.second;
                    nr.first += l.first * x;
                    nr.second += l.second * x;
                }
                std::swap(l, nl);
                std::swap(r, nr);
                break;
            }
            std::swap(l, nl);
            std::swap(r, nr);
            is_right = !is_right;
        }
        return {l, r};
    }

    static Fraction best_rational_within_an_interval(Fraction l, Fraction r) {
        Fraction m = lca(l, r);
        if (l == m) {
            Fraction rch = childs(l).second;
            if (rch == r) {
                return childs(r).first;
            } else {
                return rch;
            }
        } else if (r == m) {
            Fraction lch = childs(r).first;
            if (lch == l) {
                return childs(l).second;
            } else {
                return lch;
            }
        } else {
            return m;
        }
    }

    static std::vector<std::pair<Fraction, int>>
    lca_based_auxiliary_tree_euler_tour_order(std::vector<Fraction> fs) {
        if (fs.empty()) return {};
        euler_tour_order(fs);
        fs.erase(std::unique(fs.begin(), fs.end()), fs.end());
        int n = (int)fs.size();
        for (int i = 0; i < n - 1; i++) {
            fs.emplace_back(lca(fs[i], fs[i + 1]));
        }
        euler_tour_order(fs);
        fs.erase(std::unique(fs.begin(), fs.end()), fs.end());
        n = (int)fs.size();
        std::vector<std::pair<Fraction, int>> tree(n);
        std::vector<int> stack = {0};
        tree[0] = {fs[0], -1};
        for (int i = 1; i < n; i++) {
            while (!in_subtree(fs[i], fs[stack.back()])) {
                stack.pop_back();
            }
            tree[i] = {fs[i], stack.back()};
            stack.emplace_back(i);
        }
        return tree;
    }

    static std::pair<Fraction, Fraction> childs(Fraction f) {
        auto [l, r] = range(f);
        return {add(l, f), add(f, r)};
    }

    static bool in_subtree(Fraction f, Fraction g) {
        auto [l, r] = range(g);
        return compare(l, f) && compare(f, r);
    }

    static T depth(Fraction f) {
        T d = 0;
        for (auto n : encode_path(f)) d += n;
        return d;
    }

    static Fraction val(const std::pair<Fraction, Fraction> &f) {
        return add(f.first, f.second);
    }

    static void print_path(const std::vector<T> &path) {
        if (path.empty()) {
            std::cout << "0\n";
            return;
        }
        int k = (int)path.size() - int(path[0] == 0);
        std::cout << k;
        for (bool is_right = true; auto c : path) {
            if (c > 0) {
                std::cout << " " << (is_right ? 'R' : 'L') << " " << c;
            }
            is_right = !is_right;
        }
        std::cout << '\n';
        return;
    }
};

}  // namespace ebi
#line 1 "template/template.hpp"
#include <bits/stdc++.h>

#define rep(i, a, n) for (int i = (int)(a); i < (int)(n); i++)
#define rrep(i, a, n) for (int i = ((int)(n)-1); i >= (int)(a); i--)
#define Rep(i, a, n) for (i64 i = (i64)(a); i < (i64)(n); i++)
#define RRep(i, a, n) for (i64 i = ((i64)(n)-i64(1)); i >= (i64)(a); i--)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()

#line 2 "template/debug_template.hpp"

#line 4 "template/debug_template.hpp"

namespace ebi {

#ifdef LOCAL
#define debug(...)                                                      \
    std::cerr << "LINE: " << __LINE__ << "  [" << #__VA_ARGS__ << "]:", \
        debug_out(__VA_ARGS__)
#else
#define debug(...)
#endif

void debug_out() {
    std::cerr << std::endl;
}

template <typename Head, typename... Tail> void debug_out(Head h, Tail... t) {
    std::cerr << " " << h;
    if (sizeof...(t) > 0) std::cerr << " :";
    debug_out(t...);
}

}  // namespace ebi
#line 2 "template/int_alias.hpp"

#line 4 "template/int_alias.hpp"

namespace ebi {

using ld = long double;
using std::size_t;
using i8 = std::int8_t;
using u8 = std::uint8_t;
using i16 = std::int16_t;
using u16 = std::uint16_t;
using i32 = std::int32_t;
using u32 = std::uint32_t;
using i64 = std::int64_t;
using u64 = std::uint64_t;
using i128 = __int128_t;
using u128 = __uint128_t;

}  // namespace ebi
#line 2 "template/io.hpp"

#line 7 "template/io.hpp"

namespace ebi {

template <typename T1, typename T2>
std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &pa) {
    return os << pa.first << " " << pa.second;
}

template <typename T1, typename T2>
std::istream &operator>>(std::istream &os, std::pair<T1, T2> &pa) {
    return os >> pa.first >> pa.second;
}

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &vec) {
    for (std::size_t i = 0; i < vec.size(); i++)
        os << vec[i] << (i + 1 == vec.size() ? "" : " ");
    return os;
}

template <typename T>
std::istream &operator>>(std::istream &os, std::vector<T> &vec) {
    for (T &e : vec) std::cin >> e;
    return os;
}

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::optional<T> &opt) {
    if (opt) {
        os << opt.value();
    } else {
        os << "invalid value";
    }
    return os;
}

void fast_io() {
    std::cout << std::fixed << std::setprecision(15);
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
}

}  // namespace ebi
#line 2 "template/utility.hpp"

#line 5 "template/utility.hpp"

#line 2 "graph/base.hpp"

#line 5 "graph/base.hpp"
#include <ranges>
#line 7 "graph/base.hpp"

#line 2 "data_structure/simple_csr.hpp"

#line 6 "data_structure/simple_csr.hpp"

namespace ebi {

template <class E> struct simple_csr {
    simple_csr() = default;

    simple_csr(int n, const std::vector<std::pair<int, E>>& elements)
        : start(n + 1, 0), elist(elements.size()) {
        for (auto e : elements) {
            start[e.first + 1]++;
        }
        for (auto i : std::views::iota(0, n)) {
            start[i + 1] += start[i];
        }
        auto counter = start;
        for (auto [i, e] : elements) {
            elist[counter[i]++] = e;
        }
    }

    simple_csr(const std::vector<std::vector<E>>& es)
        : start(es.size() + 1, 0) {
        int n = es.size();
        for (auto i : std::views::iota(0, n)) {
            start[i + 1] = (int)es[i].size() + start[i];
        }
        elist.resize(start.back());
        for (auto i : std::views::iota(0, n)) {
            std::copy(es[i].begin(), es[i].end(), elist.begin() + start[i]);
        }
    }

    int size() const {
        return (int)start.size() - 1;
    }

    const auto operator[](int i) const {
        return std::ranges::subrange(elist.begin() + start[i],
                                     elist.begin() + start[i + 1]);
    }
    auto operator[](int i) {
        return std::ranges::subrange(elist.begin() + start[i],
                                     elist.begin() + start[i + 1]);
    }

    const auto operator()(int i, int l, int r) const {
        return std::ranges::subrange(elist.begin() + start[i] + l,
                                     elist.begin() + start[i + 1] + r);
    }
    auto operator()(int i, int l, int r) {
        return std::ranges::subrange(elist.begin() + start[i] + l,
                                     elist.begin() + start[i + 1] + r);
    }

  private:
    std::vector<int> start;
    std::vector<E> elist;
};

}  // namespace ebi
#line 9 "graph/base.hpp"

namespace ebi {

template <class T> struct Edge {
    int from, to;
    T cost;
    int id;
};

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

    Graph(int n_) : n(n_) {}

    Graph() = default;

    void add_edge(int u, int v, cost_type c) {
        buff.emplace_back(u, edge_type{u, v, c, m});
        edges.emplace_back(edge_type{u, v, c, m++});
    }

    void add_undirected_edge(int u, int v, cost_type c) {
        buff.emplace_back(u, edge_type{u, v, c, m});
        buff.emplace_back(v, edge_type{v, u, c, m});
        edges.emplace_back(edge_type{u, v, c, m});
        m++;
    }

    void read_tree(int offset = 1, bool is_weighted = false) {
        read_graph(n - 1, offset, false, is_weighted);
    }

    void read_parents(int offset = 1) {
        for (auto i : std::views::iota(1, n)) {
            int p;
            std::cin >> p;
            p -= offset;
            add_undirected_edge(p, i, 1);
        }
        build();
    }

    void read_graph(int e, int offset = 1, bool is_directed = false,
                    bool is_weighted = false) {
        for (int i = 0; i < e; i++) {
            int u, v;
            std::cin >> u >> v;
            u -= offset;
            v -= offset;
            if (is_weighted) {
                cost_type c;
                std::cin >> c;
                if (is_directed) {
                    add_edge(u, v, c);
                } else {
                    add_undirected_edge(u, v, c);
                }
            } else {
                if (is_directed) {
                    add_edge(u, v, 1);
                } else {
                    add_undirected_edge(u, v, 1);
                }
            }
        }
        build();
    }

    void build() {
        assert(!prepared);
        csr = simple_csr<edge_type>(n, buff);
        buff.clear();
        prepared = true;
    }

    int size() const {
        return n;
    }

    int node_number() const {
        return n;
    }

    int edge_number() const {
        return m;
    }

    edge_type get_edge(int i) const {
        return edges[i];
    }

    std::vector<edge_type> get_edges() const {
        return edges;
    }

    const auto operator[](int i) const {
        return csr[i];
    }
    auto operator[](int i) {
        return csr[i];
    }

  private:
    int n, m = 0;

    std::vector<std::pair<int,edge_type>> buff;

    std::vector<edge_type> edges;
    simple_csr<edge_type> csr;
    bool prepared = false;
};

}  // namespace ebi
#line 8 "template/utility.hpp"

namespace ebi {

template <class T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

template <class T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

template <class T> T safe_ceil(T a, T b) {
    if (a % b == 0)
        return a / b;
    else if (a >= 0)
        return (a / b) + 1;
    else
        return -((-a) / b);
}

template <class T> T safe_floor(T a, T b) {
    if (a % b == 0)
        return a / b;
    else if (a >= 0)
        return a / b;
    else
        return -((-a) / b) - 1;
}

constexpr i64 LNF = std::numeric_limits<i64>::max() / 4;

constexpr int INF = std::numeric_limits<int>::max() / 2;

const std::vector<int> dy = {1, 0, -1, 0, 1, 1, -1, -1};
const std::vector<int> dx = {0, 1, 0, -1, 1, -1, 1, -1};

}  // namespace ebi
#line 5 "test/math/Stern-Brocot_Tree.test.cpp"

namespace ebi {

void main_() {
    std::string type;
    std::cin >> type;
    if (type == "ENCODE_PATH") {
        i64 a, b;
        std::cin >> a >> b;
        auto path = stern_brocot_tree::encode_path({a, b});
        stern_brocot_tree::print_path(path);
    } else if (type == "DECODE_PATH") {
        int k;
        std::cin >> k;
        std::vector<std::pair<char, i64>> path(k);
        for (auto &[c, n] : path) {
            std::cin >> c >> n;
        }
        auto lr = stern_brocot_tree::decode_path(path);
        auto f = stern_brocot_tree::val(lr);
        std::cout << f << '\n';
    } else if (type == "LCA") {
        i64 a, b, c, d;
        std::cin >> a >> b >> c >> d;
        std::cout << stern_brocot_tree::lca({a, b}, {c, d}) << '\n';
    } else if (type == "ANCESTOR") {
        i64 k, a, b;
        std::cin >> k >> a >> b;
        auto f = stern_brocot_tree::ancestor(k, {a, b});
        if (f) {
            std::cout << f.value() << '\n';
        } else {
            std::cout << "-1\n";
        }
    } else if (type == "RANGE") {
        i64 a, b;
        std::cin >> a >> b;
        std::cout << stern_brocot_tree::range({a, b}) << '\n';
    }
}

}  // namespace ebi

int main() {
    ebi::fast_io();
    int t = 1;
    std::cin >> t;
    while (t--) {
        ebi::main_();
    }
    return 0;
}
Back to top page