shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: test/unittest/math/quotients-linear.test.cpp

Depends on

Code

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

#include <cassert>
#include <iostream>
#include <limits>
#include <random>
#include <vector>
#if __cplusplus >= 202002L
#include <ranges>
#endif

#include "../../../src/math/quotients.hpp"

void check(long long n, long long m, long long a, long long b, const std::vector<QuotientRange>& expected) {
    const auto range = enumerate_quotients_linear(n, m, a, b);
    const std::vector<QuotientRange> actual(range.begin(), range.end());
    assert(actual.size() == expected.size());
    for (long long i = 0; i < static_cast<long long>(actual.size()); i++) {
        assert(actual[i].q == expected[i].q && actual[i].l == expected[i].l && actual[i].r == expected[i].r);
    }
    long long i = 0;
    for_each_quotient_linear(n, m, a, b, [&](long long q, long long l, long long r) {
        assert(i < static_cast<long long>(expected.size()));
        assert(q == expected[i].q && l == expected[i].l && r == expected[i].r);
        i++;
    });
    assert(i == static_cast<long long>(expected.size()));
}

void check_naive(long long n, long long m, long long a, long long b) {
    std::vector<QuotientRange> expected;
    for (long long x = 0; x < n; x++) {
        const long long q = static_cast<long long>(floordiv(static_cast<__int128_t>(a) * x + b, m));
        if (!expected.empty() && expected.back().q == q)
            expected.back().r = x + 1;
        else
            expected.push_back({q, x, x + 1});
    }
    check(n, m, a, b, expected);
}

#if __cplusplus >= 202002L
static_assert(std::ranges::input_range<decltype(enumerate_quotients_linear(10, 3, 1, 0))>);
#endif

int main() {
    for (long long n = 0; n <= 8; n++) {
        for (long long m = 1; m <= 6; m++) {
            for (long long a = -6; a <= 6; a++) {
                for (long long b = -6; b <= 6; b++) check_naive(n, m, a, b);
            }
        }
    }
    std::mt19937 rng(314);
    for (int t = 0; t < 10000; t++) {
        check_naive(rng() % 100, rng() % 100 + 1, static_cast<long long>(rng() % 1001) - 500,
                    static_cast<long long>(rng() % 1001) - 500);
    }
    check(10, 3, 1, 0, {{0, 0, 3}, {1, 3, 6}, {2, 6, 9}, {3, 9, 10}});
    check(4, 10, 6, 3, {{0, 0, 2}, {1, 2, 3}, {2, 3, 4}});
    const long long hi = std::numeric_limits<long long>::max(), lo = std::numeric_limits<long long>::min();
    check(hi, hi, 1, 0, {{0, 0, hi}});
    check(hi, hi, -1, 0, {{0, 0, 1}, {-1, 1, hi}});
    check(hi, 1, 0, lo, {{lo, 0, hi}});
    check_naive(100, hi, hi, hi);
    check_naive(100, hi, lo, lo);
    check_naive(2, 1, lo, 0);
    check_naive(2, hi, 1, lo);
    check_naive(100, hi, 1, lo);
    check_naive(100, hi, 1, hi);
    check_naive(2, 1, 1, hi - 1);
    check(0, 1, 1, hi, {});
    check(hi, hi, 1, hi, {{1, 0, hi}});
    const auto huge = enumerate_quotients_linear(hi, 1, 1, 0);
    auto first = huge.begin(), copy = first;
    assert((*first++).q == 0 && (*first).q == 1 && (*copy).q == 0);
    assert((*huge.begin()).q == 0);
    std::cout << "Hello World\n";
}
#line 1 "test/unittest/math/quotients-linear.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

#include <cassert>
#include <iostream>
#include <limits>
#include <random>
#include <vector>
#if __cplusplus >= 202002L
#include <ranges>
#endif

#line 2 "src/math/quotients.hpp"

/**
 * @file quotients.hpp
 * @brief 商の列挙 (floor(n / i)・floor((a x + b) / m) が一定の区間)
 */

#include <algorithm>
#line 10 "src/math/quotients.hpp"
#include <cstddef>
#include <iterator>
#line 13 "src/math/quotients.hpp"

#line 2 "src/base/functions.hpp"

/**
 * @file functions.hpp
 * @brief 汎用関数 (chmin, chmax など)
 */

#line 9 "src/base/functions.hpp"
#include <cmath>
#line 12 "src/base/functions.hpp"
#include <numeric>
#if __cplusplus >= 202002L
#include <ranges>
#endif
#include <type_traits>
#include <utility>

template <typename T1, typename T2>
inline constexpr bool chmin(T1& a, T2 b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

template <typename T1, typename T2>
inline constexpr bool chmax(T1& a, T2 b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

inline constexpr long long max(const long long& t1, const long long& t2) {
    return std::max<long long>(t1, t2);
}

inline constexpr long long min(const long long& t1, const long long& t2) {
    return std::min<long long>(t1, t2);
}

using std::abs;
using std::gcd;
using std::lcm;
using std::size;

#if __cplusplus >= 202002L
using std::midpoint;
#else
// C++20 の std::midpoint と同じ (整数は a の側に丸め、あふれない)
template <typename T>
inline constexpr std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<T, bool>, T> midpoint(T a, T b) noexcept {
    using U = std::make_unsigned_t<T>;
    if (a <= b) return static_cast<T>(a + static_cast<T>(static_cast<U>(static_cast<U>(b) - static_cast<U>(a)) >> 1));
    return static_cast<T>(a - static_cast<T>(static_cast<U>(static_cast<U>(a) - static_cast<U>(b)) >> 1));
}
template <typename T>
inline constexpr std::enable_if_t<std::is_floating_point_v<T>, T> midpoint(T a, T b) noexcept {
    constexpr T lo = std::numeric_limits<T>::min() * 2;
    constexpr T hi = std::numeric_limits<T>::max() / 2;
    const T abs_a = a < 0 ? -a : a, abs_b = b < 0 ? -b : b;
    if (abs_a <= hi && abs_b <= hi) return (a + b) / 2;
    if (abs_a < lo) return a + b / 2;
    if (abs_b < lo) return a / 2 + b;
    return a / 2 + b / 2;
}
template <typename T>
inline constexpr std::enable_if_t<std::is_object_v<T>, T*> midpoint(T* a, T* b) noexcept {
    return a + (b - a) / 2;
}
#endif

/**
 * 要素数を long long で返す (std::ssize の long long 版)
 * size() を持つ型なら、begin() と end() を持たない自作の型にも使える
 */
#if __cplusplus >= 202002L
template <typename R>
    requires requires(R& r) { std::ranges::size(r); }
inline constexpr long long len(R&& r) {
    return static_cast<long long>(std::ranges::size(r));
}
#else
template <typename C>
inline constexpr auto len(const C& c) -> decltype(static_cast<long long>(std::size(c))) {
    return static_cast<long long>(std::size(c));
}
#endif

template <typename T>
constexpr T extgcd(const T& a, const T& b, T& x, T& y) {
    T d = a;
    if (b != 0) {
        d = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    } else {
        x = 1;
        y = 0;
    }
    return d;
}

/**
 * floor(a / b) (b != 0、負の数も可)
 */
template <typename T1, typename T2>
inline constexpr std::common_type_t<T1, T2> floordiv(T1 a, T2 b) {
    return a / b - (a % b != 0 && (a < 0) != (b < 0));
}
/**
 * ceil(a / b) (b != 0、負の数も可)
 */
template <typename T1, typename T2>
inline constexpr std::common_type_t<T1, T2> ceildiv(T1 a, T2 b) {
    return a / b + (a % b != 0 && (a < 0) == (b < 0));
}
/**
 * {floor(a / b), a - b * floor(a / b)} (b != 0、負の数も可)
 * 余りは 0 または b と同じ符号になる
 */
template <typename T1, typename T2>
inline constexpr std::pair<std::common_type_t<T1, T2>, std::common_type_t<T1, T2>> divmod(T1 a, T2 b) {
    std::common_type_t<T1, T2> q = floordiv(a, b);
    return {q, a - q * b};
}

/**
 * 0 <= x < a
 */
inline constexpr bool inrange(long long x, long long a) {
    return 0 <= x && x < a;
}
/**
 * a <= x < b
 */
inline constexpr bool inrange(long long x, long long a, long long b) {
    return a <= x && x < b;
}
/**
 * 0 <= x < a and 0 <= y < b
 */
inline constexpr bool inrect(long long x, long long y, long long a, long long b) {
    return 0 <= x && x < a && 0 <= y && y < b;
}
#line 15 "src/math/quotients.hpp"

/**
 * @brief 商 q と、それをとる添字の区間 [l, r)
 */
struct QuotientRange {
    long long q;  //!< 商
    long long l;  //!< 区間の左端 (含む)
    long long r;  //!< 区間の右端 (含まない)
};

namespace internal_quotients {
struct Quotients {
    long long n = 0;
    QuotientRange current{0, 1, 1};
    bool done = true;

    void advance() {
        const long long l = current.r;
        done = l > n;
        if (!done) {
            const long long q = n / l;
            current = {q, l, n / q + 1};
        }
    }
};

struct QuotientsLinear {
    long long n = 0, m = 1, a = 0, b = 0;
    QuotientRange current{0, 0, 0};
    bool done = true;

    void advance() {
        const long long l = current.r;
        done = l == n;
        if (done) return;
        if (a == 1) {
            long long q, length;
            if (l == 0) {
                auto [initial_q, rem] = divmod(static_cast<__int128_t>(b), static_cast<__int128_t>(m));
                q = static_cast<long long>(initial_q);
                length = m - static_cast<long long>(rem);
            } else {
                assert(current.q < std::numeric_limits<long long>::max());
                q = current.q + 1;
                length = m;
            }
            current = {q, l, l + std::min(length, n - l)};
            return;
        }
        advance_general(l);
    }

    // 加算だけで進む a == 1 の更新をインライン化しやすいよう、汎用計算を分ける。
    void advance_general(long long l) {
        const __int128_t slope = a;
        auto [q, rem] = divmod(slope * l + b, static_cast<__int128_t>(m));
        assert(std::numeric_limits<long long>::min() <= q && q <= std::numeric_limits<long long>::max());
        __int128_t length = n - l;
        // 正の傾きでは次の商に届くまで、負の傾きでは余りが負になるまで進む
        if (a > 0) chmin(length, ceildiv(m - rem, slope));
        if (a < 0) chmin(length, rem / (-slope) + 1);
        current = {static_cast<long long>(q), l, l + static_cast<long long>(length)};
    }
};

// イテレータが状態を所有するため、range の寿命や別の走査に依存しない。
template <class State>
class Enumeration {
    State initial;

   public:
    explicit Enumeration(State initial) : initial(initial) {}

    class iterator {
        State state;

       public:
        using value_type = QuotientRange;
        using difference_type = std::ptrdiff_t;
        using reference = value_type;
        using pointer = void;
        using iterator_category = std::input_iterator_tag;

        iterator() = default;
        explicit iterator(State state) : state(state) { this->state.advance(); }
        value_type operator*() const { return state.current; }
        iterator& operator++() {
            state.advance();
            return *this;
        }
        iterator operator++(int) {
            auto previous = *this;
            ++*this;
            return previous;
        }
        bool operator==(const iterator& other) const {
            if (state.done || other.state.done) return state.done == other.state.done;
            return state.current.l == other.state.current.l;
        }
        bool operator!=(const iterator& other) const { return !(*this == other); }
    };

    iterator begin() const { return iterator(initial); }
    iterator end() const { return iterator(); }
};
}  // namespace internal_quotients

/**
 * @brief floor(n / i) が一定の区間を添字の昇順 (商の降順) に遅延列挙する。全体 O(sqrt(n))、追加領域 O(1)
 * @pre 0 <= n < std::numeric_limits<long long>::max()
 */
inline auto enumerate_quotients(long long n) {
    assert(0 <= n && n < std::numeric_limits<long long>::max());
    return internal_quotients::Enumeration(internal_quotients::Quotients{n});
}

/**
 * @brief x = 0, ..., n - 1 を floor((a x + b) / m) の値で区間に分け、x の昇順に遅延列挙する。全体 O(区間数)、追加領域 O(1)
 * @pre n >= 0、m >= 1、各商が long long に収まること。a, b は負でもよい
 */
inline auto enumerate_quotients_linear(long long n, long long m, long long a, long long b) {
    assert(n >= 0 && m >= 1);
    return internal_quotients::Enumeration(internal_quotients::QuotientsLinear{n, m, a, b});
}

/**
 * @brief floor(n / i) が一定の区間ごとに f(q, l, r) を呼ぶ O(sqrt(n))
 */
template <typename F>
void for_each_quotient(long long n, F f) {
    for (auto [q, l, r] : enumerate_quotients(n)) f(q, l, r);
}

/**
 * @brief floor((a x + b) / m) が一定の区間ごとに f(q, l, r) を呼ぶ O(区間数)
 */
template <typename F>
void for_each_quotient_linear(long long n, long long m, long long a, long long b, F f) {
    for (auto [q, l, r] : enumerate_quotients_linear(n, m, a, b)) f(q, l, r);
}
#line 13 "test/unittest/math/quotients-linear.test.cpp"

void check(long long n, long long m, long long a, long long b, const std::vector<QuotientRange>& expected) {
    const auto range = enumerate_quotients_linear(n, m, a, b);
    const std::vector<QuotientRange> actual(range.begin(), range.end());
    assert(actual.size() == expected.size());
    for (long long i = 0; i < static_cast<long long>(actual.size()); i++) {
        assert(actual[i].q == expected[i].q && actual[i].l == expected[i].l && actual[i].r == expected[i].r);
    }
    long long i = 0;
    for_each_quotient_linear(n, m, a, b, [&](long long q, long long l, long long r) {
        assert(i < static_cast<long long>(expected.size()));
        assert(q == expected[i].q && l == expected[i].l && r == expected[i].r);
        i++;
    });
    assert(i == static_cast<long long>(expected.size()));
}

void check_naive(long long n, long long m, long long a, long long b) {
    std::vector<QuotientRange> expected;
    for (long long x = 0; x < n; x++) {
        const long long q = static_cast<long long>(floordiv(static_cast<__int128_t>(a) * x + b, m));
        if (!expected.empty() && expected.back().q == q)
            expected.back().r = x + 1;
        else
            expected.push_back({q, x, x + 1});
    }
    check(n, m, a, b, expected);
}

#if __cplusplus >= 202002L
static_assert(std::ranges::input_range<decltype(enumerate_quotients_linear(10, 3, 1, 0))>);
#endif

int main() {
    for (long long n = 0; n <= 8; n++) {
        for (long long m = 1; m <= 6; m++) {
            for (long long a = -6; a <= 6; a++) {
                for (long long b = -6; b <= 6; b++) check_naive(n, m, a, b);
            }
        }
    }
    std::mt19937 rng(314);
    for (int t = 0; t < 10000; t++) {
        check_naive(rng() % 100, rng() % 100 + 1, static_cast<long long>(rng() % 1001) - 500,
                    static_cast<long long>(rng() % 1001) - 500);
    }
    check(10, 3, 1, 0, {{0, 0, 3}, {1, 3, 6}, {2, 6, 9}, {3, 9, 10}});
    check(4, 10, 6, 3, {{0, 0, 2}, {1, 2, 3}, {2, 3, 4}});
    const long long hi = std::numeric_limits<long long>::max(), lo = std::numeric_limits<long long>::min();
    check(hi, hi, 1, 0, {{0, 0, hi}});
    check(hi, hi, -1, 0, {{0, 0, 1}, {-1, 1, hi}});
    check(hi, 1, 0, lo, {{lo, 0, hi}});
    check_naive(100, hi, hi, hi);
    check_naive(100, hi, lo, lo);
    check_naive(2, 1, lo, 0);
    check_naive(2, hi, 1, lo);
    check_naive(100, hi, 1, lo);
    check_naive(100, hi, 1, hi);
    check_naive(2, 1, 1, hi - 1);
    check(0, 1, 1, hi, {});
    check(hi, hi, 1, hi, {{1, 0, hi}});
    const auto huge = enumerate_quotients_linear(hi, 1, 1, 0);
    auto first = huge.begin(), copy = first;
    assert((*first++).q == 0 && (*first).q == 1 && (*copy).q == 0);
    assert((*huge.begin()).q == 0);
    std::cout << "Hello World\n";
}
Back to top page