競技プログラミング用 C++ ライブラリ
math/binomial_prefix_sum_incremental_light.hpp · GitHub で見る
共通ページ · 軽量実装
二項係数の prefix sum(差分更新)の高速実装はこちら
light_combinatorics 名前空間の差分更新版です。階乗・逆階乗を通常のループで前計算します。通常版と同時に include できます。
\(\displaystyle S(n,k)=\sum_{i=0}^{k-1}\binom ni\) を、直前のクエリから差分更新して求めます。右端を含みません。クエリは呼び出した順に処理します。
#include "lib/math/binomial_prefix_sum_incremental_light.hpp"
light_combinatorics::IncrementalBinomialPrefixSum<> sum(500000);
auto other = sum;
auto a = sum.query(5, 3); // 16
auto b = sum.query(6, 3); // 22
auto c = sum.query(6, 4); // 42
auto d = other.query(5, 2); // 6
auto e = sum.binom(5, 2); // 10
| 操作 | 内容・返り値 | 計算量 |
|---|---|---|
IncrementalBinomialPrefixSum<Mint>(max_n) |
上限まで前計算。省略時は 0 | \(O(N)\) |
auto other = sum / other = sum
|
表を共有し、現在のクエリ状態をコピー。その後の状態は独立 | \(O(1)\) |
build(max_n) |
このオブジェクトだけ表を作り直し、状態を初期化 | \(O(N)\) |
max_n() |
前計算の上限 | \(O(1)\) |
query(n,k) |
\(\displaystyle\sum_{i=0}^{k-1}\binom ni\)。右端を含まない | \(O(\lvert\Delta n\rvert+\lvert\Delta k\rvert)\) |
binom(n,k) |
\(\displaystyle\binom nk\) を Mint で返す。n < 0、k < 0、n < k なら 0 |
\(O(1)\) |
Mint の既定は mint です。素数 mod の mod()・inv() と整数からの構築・加減乗算に対応する modint を指定できます。query の n は 0 以上 max_n 以下、max_n は非負で mod()・INT_MAX 未満とし、使用中に法を変更しないでください。k は std::int64_t で、内部で \([0,n+1]\) に切り詰めます。k <= 0 なら 0、k >= n+1 なら 2^n を Mint で返します。binom も、0 を返す範囲外引数を除き n <= max_n() とします。
build(max_n) は前計算と状態を作り直し、max_n() は前計算の上限を返します。初期状態は \((n,k)=(0,0)\) です。同じクエリは \(O(1)\)、離れたクエリほど更新量が増えます。
入力を読んでから、必要な最大の n をコンストラクタへ渡してください。include だけでは前計算しません。comb.hpp・COMB_MAX は不要で、通常の二項係数も binom(n,k) から取得できます。
複数の状態を使う場合は、上の auto other = sum のようにコピーすると階乗・逆階乗・2の累乗の表を共有できます。query はそれぞれ独立して動き、片方の build は他方の表や状態を変更しません。IncrementalBinomialPrefixSum<> first(n), second(n); と別々に構築した場合は、それぞれ前計算します。
行と右端が同じ方向へ動く部分は斜めの漸化式でまとめ、右端だけが1動く部分は二項係数を直接加減算します。任意順のクエリにも対応し、クエリの並べ替えは行いません。
max_n を \(N\) として、構築・build は \(O(N)\) 時間・空間と逆元計算1回、max_n() は \(O(1)\) です。
query は直前の状態との差を \(\Delta n,\Delta k\) として \(O(\lvert\Delta n\rvert+\lvert\Delta k\rvert)\) 時間・\(O(1)\) 追加空間です。
クエリ数を \(Q\)、差分の総和を \(D\) とすると全体は \(O(N+Q+D)\) 時間です。表を共有するオブジェクトが \(P\) 個なら、合計空間は \(O(N+P)\) です。コピーは \(O(1)\) 時間・追加空間、binom は \(O(1)\) 時間・追加空間です。
#ifndef BINOMIAL_PREFIX_SUM_INCREMENTAL_LIGHT_HPP
#define BINOMIAL_PREFIX_SUM_INCREMENTAL_LIGHT_HPP
#include "../components/binomial_prefix_core_light.hpp"
#include "../components/binomial_prefix_incremental_core.hpp"
namespace light_combinatorics {
template<class Mint = mint> class IncrementalBinomialPrefixSum : public binomial_prefix_detail::IncrementalPrefixSum<Mint, light_binomial_prefix_detail::Table<Mint>, false> {
using Base = binomial_prefix_detail::IncrementalPrefixSum<Mint, light_binomial_prefix_detail::Table<Mint>, false>;
public:
explicit IncrementalBinomialPrefixSum(int max_n = 0) : Base(max_n) {}
};
}
#endif
#line 1 "math/binomial_prefix_sum_incremental_light.hpp"
#line 1 "components/binomial_prefix_core_light.hpp"
#line 1 "components/factorial_table_light.hpp"
#line 1 "math/mint.hpp"
#include <cassert>
#include <istream>
#include <ostream>
#include <type_traits>
#if defined(__GNUC__) && !defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
#pragma GCC push_options
#pragma GCC optimize("O3")
#endif
namespace mint_detail {
template <class I>
constexpr bool mint_integral = std::is_integral_v<I>
#if defined(__SIZEOF_INT128__)
|| std::is_same_v<I, __int128> || std::is_same_v<I, unsigned __int128>
#endif
;
struct [[gnu::warn_unused]] Mint {
using mint = Mint;
unsigned v = 0;
[[nodiscard]] static constexpr unsigned mod() { return 998244353; }
[[nodiscard, gnu::always_inline]] static unsigned reduce(unsigned long long x) {
return (x + (unsigned long long)(unsigned(x) * 998244351u) * mod()) >> 32;
}
[[gnu::always_inline]] Mint() = default;
template <class I, std::enable_if_t<mint_integral<I>, int> = 0>
Mint(I x) {
long long r = x % (long long)mod();
if (r < 0) r += mod();
v = reduce((unsigned long long)r * 932051910);
}
[[nodiscard, gnu::always_inline]] static Mint raw(unsigned x) {
Mint a;
a.v = reduce((unsigned long long)x * 932051910);
return a;
}
[[nodiscard, gnu::always_inline]] static Mint word(unsigned x) {
Mint a;
a.v = x;
return a;
}
[[nodiscard, gnu::always_inline]] unsigned val() const {
unsigned r = reduce(v);
return r < mod() ? r : r - mod();
}
friend std::istream &operator>>(std::istream &is, Mint &x) {
long long value;
if (is >> value) x = Mint(value);
return is;
}
friend std::ostream &operator<<(std::ostream &os, const Mint &x) {
return os << x.val();
}
[[gnu::always_inline]] Mint &operator+=(Mint b) {
v += b.v;
if (v >= 2 * mod()) v -= 2 * mod();
return *this;
}
[[gnu::always_inline]] Mint &operator-=(Mint b) {
v -= b.v;
if (v >> 31) v += 2 * mod();
return *this;
}
[[gnu::always_inline]] Mint &operator*=(Mint b) {
v = reduce((unsigned long long)v * b.v);
return *this;
}
Mint &operator/=(Mint b) { return *this *= b.inv(); }
Mint &operator++() { return *this += Mint(1); }
Mint &operator--() { return *this -= Mint(1); }
Mint operator++(int) {
Mint a = *this;
++*this;
return a;
}
Mint operator--(int) {
Mint a = *this;
--*this;
return a;
}
[[nodiscard, gnu::always_inline]] Mint operator+() const { return *this; }
[[nodiscard, gnu::always_inline]] Mint operator-() const { return word(v ? 2 * mod() - v : 0); }
[[nodiscard, gnu::always_inline]] Mint operator+(Mint b) const { return Mint(*this) += b; }
[[nodiscard, gnu::always_inline]] Mint operator-(Mint b) const { return Mint(*this) -= b; }
[[nodiscard, gnu::always_inline]] Mint operator*(Mint b) const { return Mint(*this) *= b; }
[[nodiscard]] Mint operator/(Mint b) const { return Mint(*this) /= b; }
[[nodiscard, gnu::always_inline]] bool operator==(Mint b) const { return (v < mod() ? v : v - mod()) == (b.v < mod() ? b.v : b.v - mod()); }
[[nodiscard, gnu::always_inline]] bool operator!=(Mint b) const { return !(*this == b); }
template <class I, std::enable_if_t<mint_integral<I>, int> = 0>
[[nodiscard]] friend Mint operator+(I a, Mint b) { return Mint(a) + b; }
template <class I, std::enable_if_t<mint_integral<I>, int> = 0>
[[nodiscard]] friend Mint operator-(I a, Mint b) { return Mint(a) - b; }
template <class I, std::enable_if_t<mint_integral<I>, int> = 0>
[[nodiscard]] friend Mint operator*(I a, Mint b) { return Mint(a) * b; }
template <class I, std::enable_if_t<mint_integral<I>, int> = 0>
[[nodiscard]] friend Mint operator/(I a, Mint b) { return Mint(a) / b; }
template <class I, std::enable_if_t<mint_integral<I>, int> = 0>
[[nodiscard]] friend bool operator==(I a, Mint b) { return Mint(a) == b; }
template <class I, std::enable_if_t<mint_integral<I>, int> = 0>
[[nodiscard]] friend bool operator!=(I a, Mint b) { return Mint(a) != b; }
[[nodiscard]] Mint pow(long long n) const {
assert(n >= 0);
if (!n) return Mint(1);
Mint r(1), a = *this;
for (; n > 1; n >>= 1, a *= a)
if (n & 1) r *= a;
return r * a;
}
[[nodiscard, gnu::noinline]] Mint inv() const {
assert(*this != Mint(0));
Mint a2 = *this * *this, a3 = a2 * *this;
Mint a7 = a3 * a3 * *this;
Mint a31 = a7;
for (int i = 0; i < 2; ++i) a31 *= a31;
a31 *= a3;
Mint r = a7;
for (int i = 0; i < 3; ++i) r *= r;
r *= a3;
r *= r;
for (int j = 0; j < 4; ++j) {
for (int i = 0; i < 5; ++i) r *= r;
r *= a31;
}
for (int i = 0; i < 3; ++i) r *= r;
return r * a7;
}
};
} // namespace mint_detail
using mint = mint_detail::Mint;
using fps_mint = mint;
#if defined(__GNUC__) && !defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
#pragma GCC pop_options
#endif
#line 1 "components/factorial_table_generic.hpp"
#line 1 "components/barrett32.hpp"
#line 5 "components/barrett32.hpp"
#include <cstdint>
struct Barrett32 {
std::uint32_t mod;
std::uint64_t reciprocal;
explicit Barrett32(std::uint32_t m) : mod(m), reciprocal(m > 1 ? std::uint64_t((__uint128_t(1) << 64) / m) : 0) {
assert(m > 0);
}
std::uint32_t reduce(std::uint64_t x) const {
if (mod == 1) return 0;
std::uint64_t q = (__uint128_t(x) * reciprocal) >> 64, r = x - q * mod;
return r < mod ? r : r - mod;
}
std::uint32_t mul(std::uint32_t a, std::uint32_t b) const { return reduce(std::uint64_t(a) * b); }
std::uint32_t pow(std::uint32_t a, std::uint64_t e) const {
std::uint32_t r = mod == 1 ? 0 : 1;
for (; e; e >>= 1, a = mul(a, a)) if (e & 1) r = mul(r, a);
return r;
}
};
#line 5 "components/factorial_table_generic.hpp"
#include <concepts>
#line 7 "components/factorial_table_generic.hpp"
#include <limits>
#line 9 "components/factorial_table_generic.hpp"
namespace factorial_table_detail {
template<class Mint, bool Canonical = true> void build(Mint *factorial, Mint *inverse_factorial, int n) {
if constexpr (Canonical && requires(const Mint &x) { { x.val() } -> std::integral; }) {
const auto modulus = Mint::mod();
if (std::uint64_t(modulus) <= std::numeric_limits<std::uint32_t>::max()) {
Barrett32 arithmetic(modulus);
auto make = [](std::uint32_t value) { return Mint(value); };
std::uint32_t value = 1;
factorial[0] = make(value);
for (int i = 1; i <= n; ++i) {
value = arithmetic.mul(value, i);
factorial[i] = make(value);
}
inverse_factorial[n] = factorial[n].inv();
if constexpr (std::is_signed_v<decltype(inverse_factorial[n].val())>) {
std::int64_t residue = inverse_factorial[n].val() % std::int64_t(modulus);
value = residue < 0 ? residue + modulus : residue;
} else value = arithmetic.reduce(inverse_factorial[n].val());
for (int i = n; i > 0; --i) {
value = arithmetic.mul(value, i);
inverse_factorial[i - 1] = make(value);
}
return;
}
}
factorial[0] = Mint(1);
for (int i = 1; i <= n; ++i) factorial[i] = factorial[i - 1] * Mint(i);
inverse_factorial[n] = factorial[n].inv();
for (int i = n; i > 0; --i) inverse_factorial[i - 1] = inverse_factorial[i] * Mint(i);
}
}
#line 6 "components/factorial_table_light.hpp"
#include <algorithm>
#line 11 "components/factorial_table_light.hpp"
#include <vector>
namespace light_factorial_detail {
template<class Mint> struct Table {
decltype(Mint::mod()) modulus;
std::vector<Mint> factorial, inverse_factorial;
explicit Table(int max_n) : modulus(Mint::mod()) {
assert(0 <= max_n && max_n < std::numeric_limits<int>::max() && modulus > 1);
int n = static_cast<int>(std::min(std::uint64_t(max_n), std::uint64_t(modulus) - 1));
factorial.resize(n + 1), inverse_factorial.resize(n + 1);
factorial_table_detail::build<Mint, !std::is_same_v<Mint, mint>>(factorial.data(), inverse_factorial.data(), n);
}
};
}
#line 6 "components/binomial_prefix_core_light.hpp"
namespace light_binomial_prefix_detail {
template<class Mint> struct Table : light_factorial_detail::Table<Mint> {
using Base = light_factorial_detail::Table<Mint>;
using Base::factorial, Base::inverse_factorial;
std::vector<Mint> power2;
Mint half;
explicit Table(int n = 0) : Base(n) {
assert(std::uint64_t(n) < Mint::mod());
power2.resize(n + 1);
power2[0] = Mint(1);
for (int i = 1; i <= n; ++i) power2[i] = power2[i - 1] + power2[i - 1];
half = Mint((std::uint64_t(Mint::mod()) + 1) / 2);
}
void build(int n) { *this = Table(n); }
Mint binom(int n, int k) const {
if (k < 0 || k > n) return Mint(0);
return factorial[n] * inverse_factorial[k] * inverse_factorial[n - k];
}
Mint center(int n) const {
if (!n) return Mint(0);
return n & 1 ? power2[n - 1] : (power2[n] - binom(n, n / 2)) * half;
}
Mint range(int n, int l, int r) const {
assert(0 <= l && l <= r && r <= n + 1);
Mint sum(0);
for (int i = l; i < r; ++i) sum += inverse_factorial[i] * inverse_factorial[n - i];
return factorial[n] * sum;
}
};
}
#line 1 "components/binomial_prefix_incremental_core.hpp"
#line 7 "components/binomial_prefix_incremental_core.hpp"
#include <memory>
namespace binomial_prefix_detail {
template<class Mint, class Table, bool FastHalf> class IncrementalPrefixSum {
std::shared_ptr<const Table> table_;
int n_ = 0, k_ = 0;
Mint value_ = Mint(0);
Mint halve(Mint value) const {
if constexpr (FastHalf) return Mint::word((value.v + (value.v & 1) * Mint::mod()) >> 1);
else return value * table_->half;
}
public:
explicit IncrementalPrefixSum(int max_n = 0) : table_(std::make_shared<Table>(max_n)) {}
void build(int max_n) {
table_ = std::make_shared<Table>(max_n);
n_ = k_ = 0;
value_ = Mint(0);
}
int max_n() const { return int(table_->factorial.size()) - 1; }
Mint binom(int n, int k) const {
if (n < 0 || k < 0 || k > n) return Mint(0);
assert(n <= max_n());
return table_->binom(n, k);
}
[[gnu::always_inline]] Mint query(int n, std::int64_t k) {
assert(0 <= n && n <= max_n());
int m = int(std::clamp(k, std::int64_t(0), std::int64_t(n) + 1));
if (m <= 1 || m == n + 1) {
n_ = n, k_ = m;
return value_ = m == 0 ? Mint(0) : m == 1 ? Mint(1) : table_->power2[n];
}
const Table& table = *table_;
int row = n_, column = k_;
Mint value = value_;
if (column == m) {
while (row < n) value = value + value - table.binom(row++, column - 1);
while (row > n) value = halve(value + table.binom(--row, column - 1));
} else {
if (!column) row = n;
while (row < n && column < m) value = value + value + table.binom(row++, column++);
while (row > n && column > m) value = halve(value - table.binom(--row, --column));
while (row < n) value = value + value - table.binom(row++, column - 1);
if (column < m) value += column + 1 == m ? table.binom(row, column) : table.range(row, column, m);
else if (column > m) value -= m + 1 == column ? table.binom(row, m) : table.range(row, m, column);
while (row > n) value = halve(value + table.binom(--row, m - 1));
}
n_ = n, k_ = m;
return value_ = value;
}
};
}
#line 6 "math/binomial_prefix_sum_incremental_light.hpp"
namespace light_combinatorics {
template<class Mint = mint> class IncrementalBinomialPrefixSum : public binomial_prefix_detail::IncrementalPrefixSum<Mint, light_binomial_prefix_detail::Table<Mint>, false> {
using Base = binomial_prefix_detail::IncrementalPrefixSum<Mint, light_binomial_prefix_detail::Table<Mint>, false>;
public:
explicit IncrementalBinomialPrefixSum(int max_n = 0) : Base(max_n) {}
};
}