proconlib

This documentation is automatically generated by competitive-verifier/competitive-verifier

View the Project on GitHub anqooqie/proconlib

:heavy_check_mark: Stern–Brocot tree (tools/stern_brocot_tree.hpp)

It is the Stern–Brocot tree.

License

Author

Class declaration

template <tools::non_bool_integral T>
requires tools::non_bool_integral<tools::make_wider_t<tools::make_unsigned_t<T>>>
class stern_brocot_tree;

It is the Stern–Brocot tree (SBT) capable of handling queries for irreducible fractions $\displaystyle \frac{p}{q}$, where $p$ and $q$ are positive integers expressible in T. All member functions are static, and there is no constructor.

Constraints

Time Complexity

encode_path

std::vector<std::pair<char, T>> stern_brocot_tree<T>::encode_path(T p, T q);

Let $P$ be the path from $\displaystyle \frac{1}{1}$ to $\displaystyle \frac{p}{q}$ in SBT as a string, using L for leftward move and R for rightward move. It returns run-length encoded $P$ in the format $((c_0, n_0), (c_1, n_1), \ldots, (c_{k - 1}, n_{k - 1}))$ where $c_i$ is L or R, and $n_i$ is a positive integer representing the number of consecutive $c_i$s.

Constraints

Time Complexity

decode_path

template <std::ranges::input_range R>
requires std::same_as<std::remove_cvref_t<std::tuple_element_t<0, std::ranges::range_value_t<R>>>, char>
      && tools::non_bool_integral<std::tuple_element_t<1, std::ranges::range_value_t<R>>>
std::pair<T, T> stern_brocot_tree<T>::decode_path(R&& path);

Given the path from $\displaystyle \frac{1}{1}$ to $\displaystyle \frac{p}{q}$ in the format of encode_path, it returns $(p, q)$.

Constraints

Time Complexity

lca

std::pair<T, T> stern_brocot_tree<T>::lca(T p, T q, T r, T s);

It returns $(f, g)$ such that $\displaystyle \frac{f}{g}$ is the LCA of $\displaystyle \frac{p}{q}$ and $\displaystyle \frac{r}{s}$ in SBT.

Constraints

Time Complexity

ancestor

std::optional<std::pair<T, T>> stern_brocot_tree<T>::ancestor(T d, T p, T q);

It returns $(f, g)$ such that $\displaystyle \frac{f}{g}$ is the ancestor of $\displaystyle \frac{p}{q}$ with depth $d$ in SBT. If such the irreducible fraction does not exist, it returns std::nullopt.

Constraints

Time Complexity

range

std::tuple<T, T, T, T> stern_brocot_tree<T>::range(T p, T q);

The set of descendants of $\displaystyle \frac{p}{q}$ forms an open interval of rational numbers. It returns $(f, g, h, k)$ such that $\displaystyle \frac{f}{g}$ is the infimum of the interval and $\displaystyle \frac{h}{k}$ is the supremum of the interval. As an exception, when the infimum is $0$, $(f, g)$ becomes $(0, 1)$, and when the supremum is $\infty$, $(h, k)$ becomes $(1, 0)$.

Constraints

Time Complexity

Depends on

Verified with

Code

#ifndef TOOLS_STERN_BROCOT_TREE_HPP
#define TOOLS_STERN_BROCOT_TREE_HPP

#include <algorithm>
#include <cassert>
#include <concepts>
#include <numeric>
#include <optional>
#include <ranges>
#include <tuple>
#include <utility>
#include <vector>
#include "tools/ceil.hpp"
#include "tools/cmp_equal.hpp"
#include "tools/cmp_less_equal.hpp"
#include "tools/gcd.hpp"
#include "tools/make_wider.hpp"
#include "tools/make_unsigned.hpp"
#include "tools/non_bool_integral.hpp"

namespace tools {
  template <tools::non_bool_integral T>
  requires tools::non_bool_integral<tools::make_wider_t<tools::make_unsigned_t<T>>>
  class stern_brocot_tree {
    using W = tools::make_wider_t<tools::make_unsigned_t<T>>;

    template <bool EncodePath>
    static std::conditional_t<EncodePath, std::vector<std::pair<char, T>>, std::tuple<T, T, T, T>> encode_path_impl(const T p, const T q) {
      assert(p > 0);
      assert(q > 0);
      assert(tools::gcd(p, q) == 1);

      std::vector<std::pair<char, T>> path;
      char last = p < q ? 'R' : 'L'; // sentinel
      W a = 0;
      W b = 1;
      W c = 1;
      W d = 1;
      W e = 1;
      W f = 0;
      while (!(tools::cmp_equal(c, p) && tools::cmp_equal(d, q))) {
        if (last == 'R') {
          assert(a * q < p * b); // a/b < p/q
          assert(p * d < c * q); // p/q < c/d
          assert(c * f < e * d); // c/d < e/f
          const auto k = tools::ceil(c * q - p * d, p * b - a * q);
          last = 'L';
          std::tie(c, d, e, f) = std::make_tuple(k * a + c, k * b + d, (k - 1) * a + c, (k - 1) * b + d);
          if constexpr (EncodePath) {
            path.emplace_back(last, T(k));
          }
        } else {
          assert(a * d < c * b); // a/b < c/d
          assert(c * q < p * d); // c/d < p/q
          assert(p * f < e * q); // p/q < e/f
          const auto k = tools::ceil(p * d - c * q, e * q - p * f);
          last = 'R';
          std::tie(a, b, c, d) = std::make_tuple(c + (k - 1) * e, d + (k - 1) * f, c + k * e, d + k * f); 
          if constexpr (EncodePath) {
            path.emplace_back(last, T(k));
          }
        }
      }

      if constexpr (EncodePath) {
        return path;
      } else {
        return {T(a), T(b), T(e), T(f)};
      }
    }

  public:
    stern_brocot_tree() = delete;

    static std::vector<std::pair<char, T>> encode_path(const T p, const T q) {
      return tools::stern_brocot_tree<T>::encode_path_impl<true>(p, q);
    }

    template <std::ranges::input_range R>
    requires std::same_as<std::remove_cvref_t<std::tuple_element_t<0, std::ranges::range_value_t<R>>>, char>
          && tools::non_bool_integral<std::tuple_element_t<1, std::ranges::range_value_t<R>>>
    static std::pair<T, T> decode_path(R&& path) {
      W a = 0;
      W b = 1;
      W c = 1;
      W d = 1;
      W e = 1;
      W f = 0;
      for (const auto& [direction, k] : path) {
        assert(direction == 'L' || direction == 'R');
        assert(k > 0);
        if (direction == 'L') {
          std::tie(c, d, e, f) = std::make_tuple(k * a + c, k * b + d, (k - 1) * a + c, (k - 1) * b + d);
        } else {
          std::tie(a, b, c, d) = std::make_tuple(c + (k - 1) * e, d + (k - 1) * f, c + k * e, d + k * f);
        }
      }
      assert(tools::cmp_less_equal(c, std::numeric_limits<T>::max()));
      assert(tools::cmp_less_equal(d, std::numeric_limits<T>::max()));
      return {T(c), T(d)};
    }

    static std::pair<T, T> lca(const T p, const T q, const T r, const T s) {
      assert(p > 0);
      assert(q > 0);
      assert(r > 0);
      assert(s > 0);
      assert(tools::gcd(p, q) == 1);
      assert(tools::gcd(r, s) == 1);

      const auto path1 = tools::stern_brocot_tree<T>::encode_path(p, q);
      const auto path2 = tools::stern_brocot_tree<T>::encode_path(r, s);

      std::vector<std::pair<char, T>> common_path;
      for (auto it1 = path1.begin(), it2 = path2.begin(); it1 != path1.end() && it2 != path2.end(); ++it1, ++it2) {
        if (*it1 != *it2) {
          if (it1->first == it2->first) {
            common_path.emplace_back(it1->first, std::min(it1->second, it2->second));
          }
          break;
        }
        common_path.push_back(*it1);
      }

      return tools::stern_brocot_tree<T>::decode_path(common_path);
    }

    static std::optional<std::pair<T, T>> ancestor(T d, const T p, const T q) {
      assert(d >= 0);
      assert(p > 0);
      assert(q > 0);
      assert(tools::gcd(p, q) == 1);

      std::vector<std::pair<char, T>> ancestor_path;
      for (const auto& [direction, k] : tools::stern_brocot_tree<T>::encode_path(p, q)) {
        if (d == 0) break;
        ancestor_path.emplace_back(direction, std::min(k, d));
        d -= std::min(k, d);
      }
      
      if (d > 0) return std::nullopt;
      return std::make_optional(tools::stern_brocot_tree<T>::decode_path(ancestor_path));
    }

    static std::tuple<T, T, T, T> range(const T p, const T q) {
      return tools::stern_brocot_tree<T>::encode_path_impl<false>(p, q);
    }
  };
}

#endif
#line 1 "tools/stern_brocot_tree.hpp"



#include <algorithm>
#include <cassert>
#include <concepts>
#include <numeric>
#include <optional>
#include <ranges>
#include <tuple>
#include <utility>
#include <vector>
#line 1 "tools/ceil.hpp"



#line 5 "tools/ceil.hpp"
#include <type_traits>
#line 1 "tools/non_bool_integral.hpp"



#line 1 "tools/integral.hpp"



#line 1 "tools/is_integral.hpp"



#line 5 "tools/is_integral.hpp"

namespace tools {
  template <typename T>
  struct is_integral : std::is_integral<T> {};

  template <typename T>
  inline constexpr bool is_integral_v = tools::is_integral<T>::value;
}


#line 5 "tools/integral.hpp"

namespace tools {
  template <typename T>
  concept integral = tools::is_integral_v<T>;
}


#line 7 "tools/non_bool_integral.hpp"

namespace tools {
  template <typename T>
  concept non_bool_integral = tools::integral<T> && !std::same_as<std::remove_cv_t<T>, bool>;
}


#line 1 "tools/is_unsigned.hpp"



#line 5 "tools/is_unsigned.hpp"

namespace tools {
  template <typename T>
  struct is_unsigned : std::is_unsigned<T> {};

  template <typename T>
  inline constexpr bool is_unsigned_v = tools::is_unsigned<T>::value;
}


#line 8 "tools/ceil.hpp"

namespace tools {
  template <tools::non_bool_integral M, tools::non_bool_integral N>
  constexpr std::common_type_t<M, N> ceil(const M x, const N y) noexcept {
    assert(y != 0);
    if (y >= 0) {
      if (x > 0) {
        return (x - 1) / y + 1;
      } else {
        if constexpr (tools::is_unsigned_v<std::common_type_t<M, N>>) {
          return 0;
        } else {
          return x / y;
        }
      }
    } else {
      if (x >= 0) {
        if constexpr (tools::is_unsigned_v<std::common_type_t<M, N>>) {
          return 0;
        } else {
          return x / y;
        }
      } else {
        return (x + 1) / y + 1;
      }
    }
  }
}


#line 1 "tools/cmp_equal.hpp"



#line 1 "tools/is_signed.hpp"



#line 5 "tools/is_signed.hpp"

namespace tools {
  template <typename T>
  struct is_signed : std::is_signed<T> {};

  template <typename T>
  inline constexpr bool is_signed_v = tools::is_signed<T>::value;
}


#line 1 "tools/make_unsigned.hpp"



#line 5 "tools/make_unsigned.hpp"

namespace tools {
  template <typename T>
  struct make_unsigned : std::make_unsigned<T> {};

  template <typename T>
  using make_unsigned_t = typename tools::make_unsigned<T>::type;
}


#line 7 "tools/cmp_equal.hpp"

namespace tools {
  template <tools::integral T, tools::integral U>
  constexpr bool cmp_equal(const T t, const U u) noexcept {
    using UT = tools::make_unsigned_t<T>;
    using UU = tools::make_unsigned_t<U>;
    if constexpr (tools::is_signed_v<T> == tools::is_signed_v<U>) {
      return t == u;
    } else if constexpr (tools::is_signed_v<T>) {
      return t < 0 ? false : static_cast<UT>(t) == u;
    } else {
      return u < 0 ? false : t == static_cast<UU>(u);
    }
  }
}


#line 1 "tools/cmp_less_equal.hpp"



#line 1 "tools/cmp_less.hpp"



#line 7 "tools/cmp_less.hpp"

namespace tools {
  template <tools::integral T, tools::integral U>
  constexpr bool cmp_less(const T t, const U u) noexcept {
    using UT = tools::make_unsigned_t<T>;
    using UU = tools::make_unsigned_t<U>;
    if constexpr (tools::is_signed_v<T> == tools::is_signed_v<U>) {
      return t < u;
    } else if constexpr (tools::is_signed_v<T>) {
      return t < 0 ? true : static_cast<UT>(t) < u;
    } else {
      return u < 0 ? false : t < static_cast<UU>(u);
    }
  }
}


#line 6 "tools/cmp_less_equal.hpp"

namespace tools {
  template <tools::integral T, tools::integral U>
  constexpr bool cmp_less_equal(const T t, const U u) noexcept {
    return !tools::cmp_less(u, t);
  }
}


#line 1 "tools/gcd.hpp"



#line 7 "tools/gcd.hpp"

namespace tools {
  namespace detail::gcd {
    template <typename M, typename N>
    struct impl {
      constexpr decltype(auto) operator()(const M m, const N n) const noexcept(noexcept(std::gcd(m, n))) {
        return std::gcd(m, n);
      }
    };
  }

  template <typename M, typename N>
  constexpr decltype(auto) gcd(M&& m, N&& n) noexcept(noexcept(tools::detail::gcd::impl<std::remove_cvref_t<M>, std::remove_cvref_t<N>>{}(std::forward<M>(m), std::forward<N>(n)))) {
    return tools::detail::gcd::impl<std::remove_cvref_t<M>, std::remove_cvref_t<N>>{}(std::forward<M>(m), std::forward<N>(n));
  }
}


#line 1 "tools/make_wider.hpp"



#include <limits>
#line 1 "tools/make_signed.hpp"



#line 5 "tools/make_signed.hpp"

namespace tools {
  template <typename T>
  struct make_signed : std::make_signed<T> {};

  template <typename T>
  using make_signed_t = typename tools::make_signed<T>::type;
}


#line 1 "tools/uint128_t.hpp"



#line 1 "tools/detail/int128_t_and_uint128_t.hpp"



#line 6 "tools/detail/int128_t_and_uint128_t.hpp"
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#line 11 "tools/detail/int128_t_and_uint128_t.hpp"
#include <string>
#include <string_view>
#line 1 "tools/abs.hpp"



#include <cmath>
#line 7 "tools/abs.hpp"

namespace tools {
  namespace detail::abs {
    template <typename T>
    struct impl {
      constexpr decltype(auto) operator()(const T x) const noexcept(noexcept(std::abs(x))) {
        return std::abs(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) abs(T&& x) noexcept(noexcept(tools::detail::abs::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::abs::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/bit_ceil.hpp"



#include <bit>
#line 12 "tools/bit_ceil.hpp"

namespace tools {
  namespace detail::bit_ceil {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr T operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr T operator()(const T x) const noexcept(noexcept(std::bit_ceil(x))) requires tools::is_unsigned_v<T> {
        return std::bit_ceil(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) bit_ceil(T&& x) noexcept(noexcept(tools::detail::bit_ceil::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::bit_ceil::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/bit_floor.hpp"



#line 12 "tools/bit_floor.hpp"

namespace tools {
  namespace detail::bit_floor {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr T operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr T operator()(const T x) const noexcept(noexcept(std::bit_floor(x))) requires tools::is_unsigned_v<T> {
        return std::bit_floor(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) bit_floor(T&& x) noexcept(noexcept(tools::detail::bit_floor::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::bit_floor::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/bit_width.hpp"



#line 12 "tools/bit_width.hpp"

namespace tools {
  namespace detail::bit_width {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr int operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr int operator()(const T x) const noexcept(noexcept(std::bit_width(x))) requires tools::is_unsigned_v<T> {
        return std::bit_width(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) bit_width(T&& x) noexcept(noexcept(tools::detail::bit_width::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::bit_width::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/countr_zero.hpp"



#line 14 "tools/countr_zero.hpp"

namespace tools {
  namespace detail::countr_zero {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr int operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return std::min(impl<tools::make_unsigned_t<T>>{}(x), std::numeric_limits<T>::digits);
      }
      constexpr int operator()(const T x) const noexcept(noexcept(std::countr_zero(x))) requires tools::is_unsigned_v<T> {
        return std::countr_zero(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) countr_zero(T&& x) noexcept(noexcept(tools::detail::countr_zero::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::countr_zero::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/has_single_bit.hpp"



#line 12 "tools/has_single_bit.hpp"

namespace tools {
  namespace detail::has_single_bit {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr bool operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr bool operator()(const T x) const noexcept(noexcept(std::has_single_bit(x))) requires tools::is_unsigned_v<T> {
        return std::has_single_bit(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) has_single_bit(T&& x) noexcept(noexcept(tools::detail::has_single_bit::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::has_single_bit::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 1 "tools/hash_combine.hpp"



#line 6 "tools/hash_combine.hpp"

// Source: https://github.com/google/cityhash/blob/f5dc54147fcce12cefd16548c8e760d68ac04226/src/city.h
// License: MIT
// Author: Google Inc.

// Copyright (c) 2011 Google, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

namespace tools {
  template <typename T>
  void hash_combine(std::size_t& seed, const T& v) {
    static const std::hash<T> hasher;
    static constexpr std::size_t k_mul = 0x9ddfea08eb382d69ULL;
    std::size_t a = (hasher(v) ^ seed) * k_mul;
    a ^= (a >> 47);
    std::size_t b = (seed ^ a) * k_mul;
    b ^= (b >> 47);
    seed = b * k_mul;
  }
}


#line 1 "tools/now.hpp"



#include <chrono>

namespace tools {
  inline long long now() {
    return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
  }
}


#line 1 "tools/popcount.hpp"



#line 12 "tools/popcount.hpp"

namespace tools {
  namespace detail::popcount {
    template <tools::non_bool_integral T>
    struct impl {
      constexpr int operator()(const T x) const noexcept(noexcept(impl<tools::make_unsigned_t<T>>{}(x))) requires tools::is_signed_v<T> {
        assert(x >= 0);
        return impl<tools::make_unsigned_t<T>>{}(x);
      }
      constexpr int operator()(const T x) const noexcept(noexcept(std::popcount(x))) requires tools::is_unsigned_v<T> {
        return std::popcount(x);
      }
    };
  }

  template <typename T>
  constexpr decltype(auto) popcount(T&& x) noexcept(noexcept(tools::detail::popcount::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x)))) {
    return tools::detail::popcount::impl<std::remove_cvref_t<T>>{}(std::forward<T>(x));
  }
}


#line 31 "tools/detail/int128_t_and_uint128_t.hpp"

namespace tools {
  using uint128_t = unsigned __int128;
  using int128_t = __int128;

  template <>
  struct is_integral<tools::int128_t> : std::true_type {};
  template <>
  struct is_integral<tools::uint128_t> : std::true_type {};
  template <>
  struct is_integral<const tools::int128_t> : std::true_type {};
  template <>
  struct is_integral<const tools::uint128_t> : std::true_type {};
  template <>
  struct is_integral<volatile tools::int128_t> : std::true_type {};
  template <>
  struct is_integral<volatile tools::uint128_t> : std::true_type {};
  template <>
  struct is_integral<const volatile tools::int128_t> : std::true_type {};
  template <>
  struct is_integral<const volatile tools::uint128_t> : std::true_type {};

  template <>
  struct is_signed<tools::int128_t> : std::true_type {};
  template <>
  struct is_signed<tools::uint128_t> : std::false_type {};
  template <>
  struct is_signed<const tools::int128_t> : std::true_type {};
  template <>
  struct is_signed<const tools::uint128_t> : std::false_type {};
  template <>
  struct is_signed<volatile tools::int128_t> : std::true_type {};
  template <>
  struct is_signed<volatile tools::uint128_t> : std::false_type {};
  template <>
  struct is_signed<const volatile tools::int128_t> : std::true_type {};
  template <>
  struct is_signed<const volatile tools::uint128_t> : std::false_type {};

  template <>
  struct is_unsigned<tools::int128_t> : std::false_type {};
  template <>
  struct is_unsigned<tools::uint128_t> : std::true_type {};
  template <>
  struct is_unsigned<const tools::int128_t> : std::false_type {};
  template <>
  struct is_unsigned<const tools::uint128_t> : std::true_type {};
  template <>
  struct is_unsigned<volatile tools::int128_t> : std::false_type {};
  template <>
  struct is_unsigned<volatile tools::uint128_t> : std::true_type {};
  template <>
  struct is_unsigned<const volatile tools::int128_t> : std::false_type {};
  template <>
  struct is_unsigned<const volatile tools::uint128_t> : std::true_type {};

  template <>
  struct make_signed<tools::int128_t> {
    using type = tools::int128_t;
  };
  template <>
  struct make_signed<tools::uint128_t> {
    using type = tools::int128_t;
  };
  template <>
  struct make_signed<const tools::int128_t> {
    using type = const tools::int128_t;
  };
  template <>
  struct make_signed<const tools::uint128_t> {
    using type = const tools::int128_t;
  };
  template <>
  struct make_signed<volatile tools::int128_t> {
    using type = volatile tools::int128_t;
  };
  template <>
  struct make_signed<volatile tools::uint128_t> {
    using type = volatile tools::int128_t;
  };
  template <>
  struct make_signed<const volatile tools::int128_t> {
    using type = const volatile tools::int128_t;
  };
  template <>
  struct make_signed<const volatile tools::uint128_t> {
    using type = const volatile tools::int128_t;
  };

  template <>
  struct make_unsigned<tools::int128_t> {
    using type = tools::uint128_t;
  };
  template <>
  struct make_unsigned<tools::uint128_t> {
    using type = tools::uint128_t;
  };
  template <>
  struct make_unsigned<const tools::int128_t> {
    using type = const tools::uint128_t;
  };
  template <>
  struct make_unsigned<const tools::uint128_t> {
    using type = const tools::uint128_t;
  };
  template <>
  struct make_unsigned<volatile tools::int128_t> {
    using type = volatile tools::uint128_t;
  };
  template <>
  struct make_unsigned<volatile tools::uint128_t> {
    using type = volatile tools::uint128_t;
  };
  template <>
  struct make_unsigned<const volatile tools::int128_t> {
    using type = const volatile tools::uint128_t;
  };
  template <>
  struct make_unsigned<const volatile tools::uint128_t> {
    using type = const volatile tools::uint128_t;
  };

  namespace detail::int128_t {
    constexpr tools::uint128_t parse_unsigned(const std::string_view s) noexcept {
      assert(!s.empty());
      tools::uint128_t x = 0;
      std::size_t i = s[0] == '+';
      if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
        for (i += 2; i < s.size(); ++i) {
          assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
          x <<= 4;
          if ('0' <= s[i] && s[i] <= '9') {
            x |= s[i] - '0';
          } else if ('a' <= s[i] && s[i] <= 'f') {
            x |= s[i] - 'a' + 10;
          } else {
            x |= s[i] - 'A' + 10;
          }
        }
      } else {
        for (; i < s.size(); ++i) {
          assert('0' <= s[i] && s[i] <= '9');
          x *= 10;
          x += s[i] - '0';
        }
      }
      return x;
    }

    constexpr tools::int128_t parse_signed(const std::string_view s) noexcept {
      assert(!s.empty());
      tools::int128_t x = 0;
      if (s[0] == '-') {
        std::size_t i = 1;
        if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
          for (i += 2; i < s.size(); ++i) {
            assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
            x *= 16;
            if ('0' <= s[i] && s[i] <= '9') {
              x -= s[i] - '0';
            } else if ('a' <= s[i] && s[i] <= 'f') {
              x -= s[i] - 'a' + 10;
            } else {
              x -= s[i] - 'A' + 10;
            }
          }
        } else {
          for (; i < s.size(); ++i) {
            assert('0' <= s[i] && s[i] <= '9');
            x *= 10;
            x -= s[i] - '0';
          }
        }
      } else {
        std::size_t i = s[0] == '+';
        if (i + 1 < s.size() && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) {
          for (i += 2; i < s.size(); ++i) {
            assert(('0' <= s[i] && s[i] <= '9') || ('a' <= s[i] && s[i] <= 'f') || ('A' <= s[i] && s[i] <= 'F'));
            x <<= 4;
            if ('0' <= s[i] && s[i] <= '9') {
              x |= s[i] - '0';
            } else if ('a' <= s[i] && s[i] <= 'f') {
              x |= s[i] - 'a' + 10;
            } else {
              x |= s[i] - 'A' + 10;
            }
          }
        } else {
          for (; i < s.size(); ++i) {
            assert('0' <= s[i] && s[i] <= '9');
            x *= 10;
            x += s[i] - '0';
          }
        }
      }
      return x;
    }
  }
}

#define UINT128_C(c) tools::detail::int128_t::parse_unsigned(#c)
#define INT128_C(c) tools::detail::int128_t::parse_signed(#c)

inline std::istream& operator>>(std::istream& is, tools::uint128_t& x) {
  std::string s;
  is >> s;
  x = tools::detail::int128_t::parse_unsigned(s);
  return is;
}
inline std::istream& operator>>(std::istream& is, tools::int128_t& x) {
  std::string s;
  is >> s;
  x = tools::detail::int128_t::parse_signed(s);
  return is;
}

inline std::ostream& operator<<(std::ostream& os, tools::uint128_t x) {
  std::string s;
  if (x > 0) {
    while (x > 0) {
      s.push_back('0' + x % 10);
      x /= 10;
    }
  } else {
    s.push_back('0');
  }

  std::ranges::reverse(s);
  return os << s;
}
inline std::ostream& operator<<(std::ostream& os, tools::int128_t x) {
  std::string s;
  if (x > 0) {
    while (x > 0) {
      s.push_back('0' + x % 10);
      x /= 10;
    }
  } else if (x < 0) {
    while (x < 0) {
      s.push_back('0' + (-(x % 10)));
      x /= 10;
    }
    s.push_back('-');
  } else {
    s.push_back('0');
  }

  std::ranges::reverse(s);
  return os << s;
}

#if defined(__GLIBCXX__) && defined(__STRICT_ANSI__)
namespace std {
  template <>
  struct hash<tools::uint128_t> {
    std::size_t operator()(const tools::uint128_t& x) const {
      static const std::size_t seed = tools::now();

      std::size_t hash = seed;
      tools::hash_combine(hash, static_cast<std::uint64_t>(x >> 64));
      tools::hash_combine(hash, static_cast<std::uint64_t>(x & ((UINT128_C(1) << 64) - 1)));
      return hash;
    }
  };
  template <>
  struct hash<tools::int128_t> {
    std::size_t operator()(const tools::int128_t& x) const {
      static std::hash<tools::uint128_t> hasher;
      return hasher(static_cast<tools::uint128_t>(x));
    }
  };
}
#endif

namespace tools {
  template <>
  struct detail::abs::impl<tools::int128_t> {
    constexpr tools::int128_t operator()(const tools::int128_t& x) const noexcept {
      return x >= 0 ? x : -x;
    }
  };

#if defined(__GLIBCXX__) && defined(__STRICT_ANSI__)
  template <>
  struct detail::bit_ceil::impl<tools::uint128_t> {
    constexpr tools::uint128_t operator()(tools::uint128_t x) const noexcept {
      if (x <= 1) return 1;
      --x;
      x |= x >> 1;
      x |= x >> 2;
      x |= x >> 4;
      x |= x >> 8;
      x |= x >> 16;
      x |= x >> 32;
      x |= x >> 64;
      return ++x;
    }
  };

  template <>
  struct detail::bit_floor::impl<tools::uint128_t> {
    constexpr tools::uint128_t operator()(tools::uint128_t x) const noexcept {
      x |= x >> 1;
      x |= x >> 2;
      x |= x >> 4;
      x |= x >> 8;
      x |= x >> 16;
      x |= x >> 32;
      x |= x >> 64;
      return x & ~(x >> 1);
    }
  };

  template <>
  struct detail::bit_width::impl<tools::uint128_t> {
    constexpr int operator()(tools::uint128_t x) const noexcept {
      int w = 0;
      if (x & UINT128_C(0xffffffffffffffff0000000000000000)) {
        x >>= 64;
        w += 64;
      }
      if (x & UINT128_C(0xffffffff00000000)) {
        x >>= 32;
        w += 32;
      }
      if (x & UINT128_C(0xffff0000)) {
        x >>= 16;
        w += 16;
      }
      if (x & UINT128_C(0xff00)) {
        x >>= 8;
        w += 8;
      }
      if (x & UINT128_C(0xf0)) {
        x >>= 4;
        w += 4;
      }
      if (x & UINT128_C(0xc)) {
        x >>= 2;
        w += 2;
      }
      if (x & UINT128_C(0x2)) {
        x >>= 1;
        w += 1;
      }
      w += x;
      return w;
    }
  };

  template <>
  class detail::countr_zero::impl<tools::uint128_t> {
    using type = tools::uint128_t;
    static constexpr int shift = 120;
    static constexpr type magic = UINT128_C(0x01061438916347932a5cd9d3ead7b77f);
    static constexpr int ntz_table[255] = {
      128,   0,   1,  -1,   2,  -1,   8,  -1,   3,  -1,  15,  -1,   9,  -1,  22,  -1,
        4,  -1,  29,  -1,  16,  -1,  36,  -1,  10,  -1,  43,  -1,  23,  -1,  50,  -1,
        5,  -1,  33,  -1,  30,  -1,  57,  -1,  17,  -1,  64,  -1,  37,  -1,  71,  -1,
       11,  -1,  60,  -1,  44,  -1,  78,  -1,  24,  -1,  85,  -1,  51,  -1,  92,  -1,
       -1,   6,  -1,  20,  -1,  34,  -1,  48,  31,  -1,  -1,  69,  58,  -1,  -1,  90,
       18,  -1,  67,  -1,  65,  -1,  99,  -1,  38,  -1, 101,  -1,  72,  -1, 106,  -1,
       -1,  12,  -1,  40,  -1,  61,  -1,  82,  45,  -1,  -1, 103,  79,  -1, 113,  -1,
       -1,  25,  -1,  74,  86,  -1,  -1, 116,  -1,  52,  -1, 108,  -1,  93,  -1, 120,
      127,  -1,  -1,   7,  -1,  14,  -1,  21,  -1,  28,  -1,  35,  -1,  42,  -1,  49,
       -1,  32,  -1,  56,  -1,  63,  -1,  70,  -1,  59,  -1,  77,  -1,  84,  -1,  91,
       -1,  19,  -1,  47,  -1,  68,  -1,  89,  -1,  66,  -1,  98,  -1, 100,  -1, 105,
       -1,  39,  -1,  81,  -1, 102,  -1, 112,  -1,  73,  -1, 115,  -1, 107,  -1, 119,
      126,  -1,  13,  -1,  27,  -1,  41,  -1,  -1,  55,  62,  -1,  -1,  76,  83,  -1,
       -1,  46,  -1,  88,  -1,  97,  -1, 104,  -1,  80,  -1, 111,  -1, 114,  -1, 118,
      125,  -1,  26,  -1,  54,  -1,  75,  -1,  -1,  87,  96,  -1,  -1, 110,  -1, 117,
      124,  -1,  53,  -1,  -1,  95, 109,  -1, 123,  -1,  94,  -1, 122,  -1, 121
    };

  public:
    constexpr int operator()(const type& x) const noexcept {
      return ntz_table[static_cast<type>(magic * static_cast<type>(x & -x)) >> shift];
    }
  };

  namespace detail::gcd {
    template <>
    struct impl<tools::uint128_t, tools::uint128_t> {
      constexpr tools::uint128_t operator()(tools::uint128_t m, tools::uint128_t n) const noexcept {
        while (n != 0) {
          m %= n;
          std::swap(m, n);
        }
        return m;
      };
    };

    template <typename T>
    concept non_bool_integral_at_most_128bit = tools::non_bool_integral<T> && std::numeric_limits<T>::digits <= 128;
    template <typename T>
    concept non_bool_integral_at_most_64bit = tools::non_bool_integral<T> && std::numeric_limits<T>::digits <= 64;

    template <typename M, typename N> requires (
      (non_bool_integral_at_most_128bit<M> && non_bool_integral_at_most_128bit<N>)
      && !(non_bool_integral_at_most_64bit<M> && non_bool_integral_at_most_64bit<N>)
      && !(std::same_as<M, tools::uint128_t> && std::same_as<N, tools::uint128_t>)
    )
    struct impl<M, N> {
      constexpr std::common_type_t<M, N> operator()(const M m, const N n) const noexcept {
        return std::common_type_t<M, N>(
          tools::gcd(
            m >= 0 ? tools::uint128_t(m) : tools::uint128_t(-(m + 1)) + 1,
            n >= 0 ? tools::uint128_t(n) : tools::uint128_t(-(n + 1)) + 1
          )
        );
      }
    };
  }

  template <>
  struct detail::has_single_bit::impl<tools::uint128_t> {
    constexpr bool operator()(tools::uint128_t x) const noexcept {
      return x != 0 && (x & (x - 1)) == 0;
    }
  };

  template <>
  struct detail::popcount::impl<tools::uint128_t> {
    constexpr int operator()(tools::uint128_t x) const noexcept {
      x = (x & UINT128_C(0x55555555555555555555555555555555)) + (x >> 1 & UINT128_C(0x55555555555555555555555555555555));
      x = (x & UINT128_C(0x33333333333333333333333333333333)) + (x >> 2 & UINT128_C(0x33333333333333333333333333333333));
      x = (x & UINT128_C(0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f)) + (x >> 4 & UINT128_C(0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f));
      x = (x & UINT128_C(0x00ff00ff00ff00ff00ff00ff00ff00ff)) + (x >> 8 & UINT128_C(0x00ff00ff00ff00ff00ff00ff00ff00ff));
      x = (x & UINT128_C(0x0000ffff0000ffff0000ffff0000ffff)) + (x >> 16 & UINT128_C(0x0000ffff0000ffff0000ffff0000ffff));
      x = (x & UINT128_C(0x00000000ffffffff00000000ffffffff)) + (x >> 32 & UINT128_C(0x00000000ffffffff00000000ffffffff));
      x = (x & UINT128_C(0x0000000000000000ffffffffffffffff)) + (x >> 64 & UINT128_C(0x0000000000000000ffffffffffffffff));
      return x;
    }
  };
#endif
}


#line 5 "tools/uint128_t.hpp"


#line 11 "tools/make_wider.hpp"

namespace tools {
  namespace detail::make_wider {
    template <typename T>
    struct safe_make_signed {
      using type = tools::make_signed_t<T>;
    };
    template <>
    struct safe_make_signed<void> {
      using type = void;
    };
    template <typename T>
    using safe_make_signed_t = typename safe_make_signed<T>::type;
  }

  template <tools::non_bool_integral T>
  class make_wider {
    using R = std::remove_cv_t<T>;
    using U = tools::make_unsigned_t<R>;
    using W = std::conditional_t<std::numeric_limits<U>::digits * 2 <= std::numeric_limits<unsigned char>::digits, unsigned char,
              std::conditional_t<std::numeric_limits<U>::digits * 2 <= std::numeric_limits<unsigned short>::digits, unsigned short,
              std::conditional_t<std::numeric_limits<U>::digits * 2 <= std::numeric_limits<unsigned int>::digits, unsigned int,
              std::conditional_t<std::numeric_limits<U>::digits * 2 <= std::numeric_limits<unsigned long>::digits, unsigned long,
              std::conditional_t<std::numeric_limits<U>::digits * 2 <= std::numeric_limits<unsigned long long>::digits, unsigned long long,
              std::conditional_t<std::numeric_limits<U>::digits * 2 <= std::numeric_limits<tools::uint128_t>::digits, tools::uint128_t,
              void>>>>>>;
    using signedness_recovered = std::conditional_t<tools::is_signed_v<R>, tools::detail::make_wider::safe_make_signed_t<W>, W>;
    using const_recovered = std::conditional_t<std::is_const_v<T>, std::add_const_t<signedness_recovered>, signedness_recovered>;
    using volatile_recovered = std::conditional_t<std::is_volatile_v<T>, std::add_volatile_t<const_recovered>, const_recovered>;

  public:
    using type = volatile_recovered;
  };

  template <tools::non_bool_integral T>
  using make_wider_t = typename tools::make_wider<T>::type;
}


#line 20 "tools/stern_brocot_tree.hpp"

namespace tools {
  template <tools::non_bool_integral T>
  requires tools::non_bool_integral<tools::make_wider_t<tools::make_unsigned_t<T>>>
  class stern_brocot_tree {
    using W = tools::make_wider_t<tools::make_unsigned_t<T>>;

    template <bool EncodePath>
    static std::conditional_t<EncodePath, std::vector<std::pair<char, T>>, std::tuple<T, T, T, T>> encode_path_impl(const T p, const T q) {
      assert(p > 0);
      assert(q > 0);
      assert(tools::gcd(p, q) == 1);

      std::vector<std::pair<char, T>> path;
      char last = p < q ? 'R' : 'L'; // sentinel
      W a = 0;
      W b = 1;
      W c = 1;
      W d = 1;
      W e = 1;
      W f = 0;
      while (!(tools::cmp_equal(c, p) && tools::cmp_equal(d, q))) {
        if (last == 'R') {
          assert(a * q < p * b); // a/b < p/q
          assert(p * d < c * q); // p/q < c/d
          assert(c * f < e * d); // c/d < e/f
          const auto k = tools::ceil(c * q - p * d, p * b - a * q);
          last = 'L';
          std::tie(c, d, e, f) = std::make_tuple(k * a + c, k * b + d, (k - 1) * a + c, (k - 1) * b + d);
          if constexpr (EncodePath) {
            path.emplace_back(last, T(k));
          }
        } else {
          assert(a * d < c * b); // a/b < c/d
          assert(c * q < p * d); // c/d < p/q
          assert(p * f < e * q); // p/q < e/f
          const auto k = tools::ceil(p * d - c * q, e * q - p * f);
          last = 'R';
          std::tie(a, b, c, d) = std::make_tuple(c + (k - 1) * e, d + (k - 1) * f, c + k * e, d + k * f); 
          if constexpr (EncodePath) {
            path.emplace_back(last, T(k));
          }
        }
      }

      if constexpr (EncodePath) {
        return path;
      } else {
        return {T(a), T(b), T(e), T(f)};
      }
    }

  public:
    stern_brocot_tree() = delete;

    static std::vector<std::pair<char, T>> encode_path(const T p, const T q) {
      return tools::stern_brocot_tree<T>::encode_path_impl<true>(p, q);
    }

    template <std::ranges::input_range R>
    requires std::same_as<std::remove_cvref_t<std::tuple_element_t<0, std::ranges::range_value_t<R>>>, char>
          && tools::non_bool_integral<std::tuple_element_t<1, std::ranges::range_value_t<R>>>
    static std::pair<T, T> decode_path(R&& path) {
      W a = 0;
      W b = 1;
      W c = 1;
      W d = 1;
      W e = 1;
      W f = 0;
      for (const auto& [direction, k] : path) {
        assert(direction == 'L' || direction == 'R');
        assert(k > 0);
        if (direction == 'L') {
          std::tie(c, d, e, f) = std::make_tuple(k * a + c, k * b + d, (k - 1) * a + c, (k - 1) * b + d);
        } else {
          std::tie(a, b, c, d) = std::make_tuple(c + (k - 1) * e, d + (k - 1) * f, c + k * e, d + k * f);
        }
      }
      assert(tools::cmp_less_equal(c, std::numeric_limits<T>::max()));
      assert(tools::cmp_less_equal(d, std::numeric_limits<T>::max()));
      return {T(c), T(d)};
    }

    static std::pair<T, T> lca(const T p, const T q, const T r, const T s) {
      assert(p > 0);
      assert(q > 0);
      assert(r > 0);
      assert(s > 0);
      assert(tools::gcd(p, q) == 1);
      assert(tools::gcd(r, s) == 1);

      const auto path1 = tools::stern_brocot_tree<T>::encode_path(p, q);
      const auto path2 = tools::stern_brocot_tree<T>::encode_path(r, s);

      std::vector<std::pair<char, T>> common_path;
      for (auto it1 = path1.begin(), it2 = path2.begin(); it1 != path1.end() && it2 != path2.end(); ++it1, ++it2) {
        if (*it1 != *it2) {
          if (it1->first == it2->first) {
            common_path.emplace_back(it1->first, std::min(it1->second, it2->second));
          }
          break;
        }
        common_path.push_back(*it1);
      }

      return tools::stern_brocot_tree<T>::decode_path(common_path);
    }

    static std::optional<std::pair<T, T>> ancestor(T d, const T p, const T q) {
      assert(d >= 0);
      assert(p > 0);
      assert(q > 0);
      assert(tools::gcd(p, q) == 1);

      std::vector<std::pair<char, T>> ancestor_path;
      for (const auto& [direction, k] : tools::stern_brocot_tree<T>::encode_path(p, q)) {
        if (d == 0) break;
        ancestor_path.emplace_back(direction, std::min(k, d));
        d -= std::min(k, d);
      }
      
      if (d > 0) return std::nullopt;
      return std::make_optional(tools::stern_brocot_tree<T>::decode_path(ancestor_path));
    }

    static std::tuple<T, T, T, T> range(const T p, const T q) {
      return tools::stern_brocot_tree<T>::encode_path_impl<false>(p, q);
    }
  };
}


Back to top page