library_for_cpp

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

View the Project on GitHub Kazun1998/library_for_cpp

:heavy_check_mark: Lagrange 補間
(Math/Lagrange_Interpolation.hpp)

Outline

$(d+1)$ 個の点 $(x_0, y_0), (x_1, y_1), \dots, (x_d, y_d)$ について, $(d+1)$ 個の条件

\[f(x_i) = y_i \quad (0 \leq i \leq d)\]

を満たす $d$ 次以下の多項式 $f$ に関する値を求める.

Theory

Lagrange 多項式を使った, 多項式の決定

$F$ を体とする.

$(d+1)$ 個の点 $(x_0, y_0), (x_1, y_1), \dots, (x_d, y_d)$ について, $x_0, x_1, \dots, x_d$ は互いに異なるとする. このとき,

\[f(x_i) = y_i \quad (0 \leq i \leq d)\]

を満たす $d$ 次以下の多項式 $f$ はただ $1$ つ存在する. 証明は Vandermonde 行列が正則であることから従う.


$i = 0, 1, \dots, d$ に対して, Lagrange 多項式 $\ell_i(x)$ を

\[\ell_i(x) := \prod_{\substack{0 \leq j \leq d \\ j \neq i}} \dfrac{x - x_j}{x_i - x_j}\]

で定める. このとき, $i, j \in \{0, 1, \dots, d \}$ に対して,

\[\ell_i(x_j) = \delta_{i, j}\]

が成り立つ.

このとき, 多項式 $g$ を

\[g(x) := \sum_{i=0}^d y_i \ell_i(x)\]

で定めると,

\[g(x_j) = \sum_{i=0}^d y_i \ell_i(x_j) = \sum_{i=0}^d y_i \delta_{i,j} = y_j\]

である. ただし, $\delta_{i,j}$ は Kronecker Delta.

よって, $f, g$ は相異なる $(d+1)$ 個の点で一致する $d$ 次以下の多項式であるため, $f = g$ が成り立つ. 故に,

\[f(x) = \sum_{i=0}^d y_i \ell_i(x)\]

である.

特定の一点における値

$(d+1)$ 個の点 $(x_0, y_0), (x_1, y_1), \dots, (x_d, y_d)$ について, $(d+1)$ 個の条件

\[f(x_i) = y_i \quad (0 \leq i \leq d)\]

を満たす $d$ 次以下の多項式 $f$ に関する $f(s)$ の値を求める.

各 $i$ に対して, $\ell_i(s)$ は $O(d)$ 時間で求められる. 故に,

\[f(s) = \sum_{i=0}^d y_i \ell_i(s)\]

であるため, $f(s)$ は $O(d^2)$ 時間で求められる.

多項式の各係数を求める

多項式 $m(x)$ を

\[m(x) := \prod_{i=0}^d (x - x_i)\]

と置く. この $m(x)$ は $O(d^2)$ 時間で求めることができる. このとき,

\[\ell_i(x) = \dfrac{1}{m'(x_i)} \cdot \dfrac{m(x)}{x - x_i}\]

である.

ここで $m’(x_i) = \prod_{j \neq i} (x_i - x_j)$ であり, これは $m(x)$ を微分した多項式 $m’(x)$ に $x = x_i$ を代入することで得られる.

各 $i$ について, 微分係数 $m’(x_i)$ の計算に $O(d)$ 時間, 多項式の除算(組立除法)に $O(d)$ かかるため, 各 $\ell_i(x)$ は $O(d)$ 時間で求められる.

これを $(d+1)$ 個足し合わせるため, 全体の計算量は $O(d^2)$ 時間である。

故に, 各 $\ell_i(x)$ は $O(d)$ 時間で求められ, これを $(d+1)$ 個合計するため, 合計の時間計算量は $O(d^2)$ 時間である.

標本点が等差数列のとき

もし, 標本点 $x_i$ が等差数列 $x_i = ai + b$ を満たしているならば, 特定の点 $f(s)$ を求める計算量は $O(d^2)$ 時間から, $O(d)$ 時間に大きく落ちる.

Lagrange 多項式の値 $\ell_i(s)$ について,

\[\begin{align*} \ell_i(s) &= \prod_{\substack{0 \leq j \leq d \\ j \neq i}} \dfrac{s - x_j}{x_i - x_j} \\ &= \prod_{\substack{0 \leq j \leq d \\ j \neq i}} \dfrac{s - (aj+b)}{(ai+b) - (aj+b)} \\ &= \prod_{\substack{0 \leq j \leq d \\ j \neq i}} \dfrac{s - (aj+b)}{a(i-j)} \\ &= \dfrac{1}{a^d} \prod_{\substack{0 \leq j \leq d \\ j \neq i}} \dfrac{s - (aj+b)}{i-j} \end{align*}\]

である. ここで,

\[\varepsilon_j := s - (a j + b)\]

とおくと,

\[\begin{align*} \ell_i(s) &= \dfrac{1}{a^d} \prod_{\substack{0 \leq j \leq d \\ j \neq i}} \dfrac{s - (aj+b)}{i-j} \\ &= \dfrac{1}{a^d} \prod_{\substack{0 \leq j \leq d \\ j \neq i}} \dfrac{\varepsilon_j}{i-j} \\ &= \dfrac{1}{a^d} \cdot \dfrac{\left(\varepsilon_0 \varepsilon_1 \dots \varepsilon_{i-1} \right) \left(\varepsilon_{i+1} \varepsilon_{i+2} \dots \varepsilon_{d} \right) }{i \cdot (i-1) \dots 1 \cdot (-1) \cdot (-2) \dots (-(i-d))} \\ &= \dfrac{1}{a^d} \cdot \dfrac{\left(\varepsilon_0 \varepsilon_1 \dots \varepsilon_{i-1} \right) \left(\varepsilon_{i+1} \varepsilon_{i+2} \dots \varepsilon_{d} \right) }{i! \cdot (d-i)! \cdot (-1)^{d-i}} \\ &= \dfrac{(-1)^i}{(-a)^d} \cdot \dfrac{\left(\varepsilon_0 \varepsilon_1 \dots \varepsilon_{i-1} \right) \left(\varepsilon_{i+1} \varepsilon_{i+2} \dots \varepsilon_{d} \right) }{i! \cdot (d-i)!} \end{align*}\]

である.

\[\textrm{prefix}_i := \varepsilon_0 \varepsilon_1 \dots \varepsilon_i, \quad \textrm{suffix}_i := \varepsilon_i \varepsilon_{i+1} \dots \varepsilon_d\]

とおくと,

\[\ell_i(s) = \dfrac{(-1)^i}{(-a)^d} \cdot \dfrac{\textrm{prefix}_{i-1} \cdot \textrm{suffix}_{i+1} }{i! \cdot (d-i)!}\]

である.

$\textrm{prefix}_i, \textrm{suffix}_i$ はそれぞれ順番に注意して累積的に計算することにより, $i=0,1,\dots,d$ を合計で $O(d)$ 時間で求められる.

階乗の逆元も, $(0!)^{-1}, (1!)^{-1}, \dots, (d!)^{-1}$ を合計で $O(d)$ 時間で求められる.

以上から, 前計算 $O(d)$ 時間の元で $0 \leq i \leq d$ における $\ell_i(s)$ をで各 $O(1)$ 時間で求められる.

故に, $f(s)$ を $O(d)$ 時間で求められる.

History

日付 内容
2026/04/18 Lagrange 補間に関するメソッドの実装

Depends on

Required by

Verified with

Code

#pragma once

#include "../template/template.hpp"
#include "../template/enumerable.hpp"
#include "../Counting/Combination_Calculator.hpp"

/**
 * @brief ラグランジュ補間を用いた評価点の値の計算 (O(N^2))
 * @details 与えられた n 個の点 (x[i], y[i]) を通る n-1 次以下の多項式 P に対し、P(X) を求める。
 * @tparam F 体を表す型 (ModInt 等)
 * @param x 点の x 座標のリスト (すべて異なる必要がある)
 * @param y 点の y 座標のリスト
 * @param X 評価点
 * @return F P(X) の値
 */
template<typename F>
F Lagrange_Interpolation_Point(const vector<F> &x, const vector<F> &y, F X) {
    assert(x.size() == y.size());
    int n = (int)x.size();

    // 分子の累積積を前計算 O(N)
    vector<F> pre(n + 1, F(1)), suf(n + 1, F(1));
    for (int i = 0; i < n; ++i) pre[i + 1] = pre[i] * (X - x[i]);
    for (int i = n - 1; i >= 0; --i) suf[i] = suf[i + 1] * (X - x[i]);

    F Y = F(0);
    for (int i = 0; i < n; ++i) {
        // 分母の積を計算
        F den = F(1);
        for (int j = 0; j < n; ++j) {
            if (i == j) continue;

            den *= (x[i] - x[j]);
        }

        Y += y[i] * pre[i] * suf[i + 1] / den;
    }

    return Y;
}

/**
 * @brief ラグランジュ補間を用いた評価点の値の計算 (O(N^2))
 * @details points[i] = (x_i, y_i) を通る n-1 次以下の多項式 P に対し、P(X) を求める。
 * @tparam F 体を表す型
 * @param points 点 (x, y) のリスト
 * @param X 評価点
 * @return F P(X) の値
 */
template<typename F>
F Lagrange_Interpolation_Point(const vector<pair<F, F>> &points, F X) {
    auto x = enumerable::collect(points, [](const auto &p) { return p.first; });
    auto y = enumerable::collect(points, [](const auto &p) { return p.second; });
    return Lagrange_Interpolation_Point(x, y, X);
}

/**
 * @brief ラグランジュ補間を用いた多項式の係数の決定 (O(N^2))
 * @details 与えられた n 個の点 (x[i], y[i]) を通る n-1 次以下の多項式 P(x) = \sum res[i] * x^i を求める。
 * @tparam F 体を表す型
 * @param x 点の x 座標のリスト (すべて異なる必要がある)
 * @param y 点の y 座標のリスト
 * @return vector<F> 多項式の係数リスト res (res[i] は x^i の係数)
 */
template<typename F>
vector<F> Lagrange_Interpolation_Polynomial(const vector<F> &x, const vector<F> &y) {
    assert(x.size() == y.size());
    int n = (int)x.size();
    if (n == 0) return {};

    // Section I: m(x) = \prod (x - xs[i]) を計算
    vector<F> m(n + 1, 0);
    m[0] = 1;
    for (int i = 0; i < n; ++i) {
        for (int j = i; j >= 0; --j) {
            m[j + 1] += m[j];
            m[j] *= -x[i];
        }
    }

    // Section II: m の導関数 m' を求める.
    vector<F> m_diff(n);
    for (int i = 1; i <= n; ++i) {
        m_diff[i - 1] = F(i) * m[i];
    }

    // Section III: f を求める.
    vector<F> res(n, 0);
    for (int i = 0; i < n; ++i) {
        // Evaluate m'(x[i]) using Horner's method
        F val_diff = 0;
        for (int j = n - 1; j >= 0; --j) {
            val_diff = val_diff * x[i] + m_diff[j];
        }

        F weight = y[i] / val_diff;

        // Compute Q_i(x) = m(x) / (x - x[i]) and add weight * Q_i(x) to res
        F q = m[n];
        for (int j = n - 1; j >= 0; --j) {
            res[j] += weight * q;
            q = m[j] + x[i] * q;
        }
    }
    return res;
}

/**
 * @brief ラグランジュ補間を用いた多項式の係数の決定 (O(N^2))
 * @details points[i] = (x_i, y_i) を通る n-1 次以下の多項式 P(x) = \sum res[i] * x^i を求める。
 * @tparam F 体を表す型
 * @param points 点 (x, y) のリスト
 * @return vector<F> 多項式の係数リスト res (res[i] は x^i の係数)
 */
template<typename F>
vector<F> Lagrange_Interpolation_Polynomial(const vector<pair<F, F>> &points) {
    auto x = enumerable::collect(points, [](const auto &p) { return p.first; });
    auto y = enumerable::collect(points, [](const auto &p) { return p.second; });
    return Lagrange_Interpolation_Polynomial(x, y);
}

/**
 * @brief 等差数列上の点におけるラグランジュ補間 (O(N))
 * @details 多項式 P(a*i + b) = y[i] (0 <= i < |y|) を満たす P(s) を求める。
 * @tparam F 体を表す型 (ModInt 等)
 * @param a 等差数列の公差
 * @param b 等差数列の初項
 * @param y 各点における多項式の値のリスト
 * @param s 評価点
 * @return F P(s) の値
 */
template<typename F>
F Lagrange_Interpolation_Point_Arithmetic(const F a, const F b, const vector<F> &y, const F s) {
    int n = (int)y.size();
    if (n == 0) return F(0);
    if (n == 1) return y[0];
    int d = n - 1;

    // 階乗の逆元を計算
    vector<F> inv_fact(n);
    {
        F f = 1;
        for (int i = 2; i <= d; ++i) f *= i;
        inv_fact[d] = F(1) / f;
        for (int i = d; i >= 1; --i) inv_fact[i - 1] = inv_fact[i] * i;
    }

    // 右からの累積積を計算
    vector<F> suffix(n);
    {
        F cur_x = b + a * d;
        for (int i = d; i >= 0; --i) {
            suffix[i] = (i == d ? s - cur_x : suffix[i + 1] * (s - cur_x));
            cur_x -= a;
        }
    }

    // coef = (-a)^{-d}
    F coef = (a == F(1)) ? ((d & 1) ? F(-1) : F(1)) : pow(-a, -d);

    F t = 0;
    F running_prefix = 1;
    F cur_x = b;
    for (int i = 0; i < n; ++i) {
        F suf = (i == d) ? 1 : suffix[i + 1];

        F alpha = running_prefix * suf * inv_fact[i] * inv_fact[d - i];
        if (is_odd(i)) t -= y[i] * alpha;
        else t += y[i] * alpha;

        running_prefix *= (s - cur_x);
        cur_x += a;
    }

    return coef * t;
}

/**
 * @brief 連続する整数点におけるラグランジュ補間 (O(N))
 * @details 多項式 P(i) = y[i] (0 <= i < |y|) を満たす P(s) を求める。
 * @tparam F 体を表す型 (ModInt 等)
 * @param y 各点における多項式の値のリスト (x = 0, 1, ..., |y|-1)
 * @param s 評価点
 * @return F P(s) の値
 */
template<typename F>
F Lagrange_Interpolation_Point_Arithmetic(const vector<F> &y, const F s) {
    return Lagrange_Interpolation_Point_Arithmetic<F>(1, 0, y, s);
}
#line 2 "Math/Lagrange_Interpolation.hpp"

#line 2 "template/template.hpp"

using namespace std;

// intrinstic
#include <immintrin.h>

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfenv>
#include <cfloat>
#include <chrono>
#include <cinttypes>
#include <climits>
#include <cmath>
#include <complex>
#include <concepts>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <iomanip>
#include <ios>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <optional>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <streambuf>
#include <string>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

// utility
#line 2 "template/utility.hpp"

using ll = long long;

// a ← max(a, b) を実行する. a が更新されたら, 返り値が true.
template<typename T, typename U>
inline bool chmax(T &a, const U b){
    return (a < b ? a = b, 1: 0);
}

// a ← min(a, b) を実行する. a が更新されたら, 返り値が true.
template<typename T, typename U>
inline bool chmin(T &a, const U b){
    return (a > b ? a = b, 1: 0);
}

// a の最大値を取得する.
template<typename T>
inline T max(const vector<T> &a){
    if (a.empty()) throw invalid_argument("vector is empty.");

    return *max_element(a.begin(), a.end());
}

// vector<T> a の最小値を取得する.
template<typename T>
inline T min(const vector<T> &a){
    if (a.empty()) throw invalid_argument("vector is empty.");

    return *min_element(a.begin(), a.end());
}

// vector<T> a の最大値のインデックスを取得する.
template<typename T>
inline size_t argmax(const vector<T> &a){
    if (a.empty()) throw std::invalid_argument("vector is empty.");

    return distance(a.begin(), max_element(a.begin(), a.end()));
}

// vector<T> a の最小値のインデックスを取得する.
template<typename T>
inline size_t argmin(const vector<T> &a){
    if (a.empty()) throw invalid_argument("vector is empty.");

    return distance(a.begin(), min_element(a.begin(), a.end()));
}
#line 61 "template/template.hpp"

// math
#line 2 "template/math.hpp"

// 演算子
template<typename T>
T add(const T &x, const T &y) { return x + y; }

template<typename T>
T sub(const T &x, const T &y) { return x - y; }

template<typename T>
T mul(const T &x, const T &y) { return x * y; }

template<typename T>
T neg(const T &x) { return -x; }

template<integral T>
T bitwise_and(const T &x, const T &y) { return x & y; }

template<integral T>
T bitwise_or(const T &x, const T &y) { return x | y; }

template<integral T>
T bitwise_xor(const T &x, const T &y) { return x ^ y; }

// 除算に関する関数

// floor(x / y) を求める.
template<integral T, integral U>
auto div_floor(T x, U y){
    return x / y - ((x % y != 0) && ((x < 0) != (y < 0)));
}

// ceil(x / y) を求める.
template<integral T, integral U>
auto div_ceil(T x, U y){
    return x / y + ((x % y != 0) && ((x < 0) == (y < 0)));
}

// x を y で割った余りを求める.
template<integral T, integral U>
auto safe_mod(T x, U y){
    auto q = div_floor(x, y);
    return x - q * y ;
}

// x を y で割った商と余りを求める.
template<integral T, integral U>
auto divmod(T x, U y){
    auto q = div_floor(x, y);
    return make_pair(q, x - q * y);
}

// 四捨五入を求める.
template<integral T, integral U>
auto round(T x, U y){
    auto [q, r] = divmod(x, y);
    if (y < 0) return (r <= div_floor(y, 2)) ? q + 1 : q;
    return (r >= div_ceil(y, 2)) ? q + 1 : q;
}

// 奇数かどうか判定する.
template<integral T>
bool is_odd(const T &x) { return x % 2 != 0; }

// 偶数かどうか判定する.
template<integral T>
bool is_even(const T &x) { return x % 2 == 0; }

// m の倍数かどうか判定する.
template<integral T, integral U>
bool is_multiple(const T &x, const U &m) { return x % m == 0; }

// 正かどうか判定する.
template<typename T>
bool is_positive(const T &x) { return x > 0; }

// 負かどうか判定する.
template<typename T>
bool is_negative(const T &x) { return x < 0; }

// ゼロかどうか判定する.
template<typename T>
bool is_zero(const T &x) { return x == 0; }

// 非負かどうか判定する.
template<typename T>
bool is_non_negative(const T &x) { return x >= 0; }

// 非正かどうか判定する.
template<typename T>
bool is_non_positive(const T &x) { return x <= 0; }

// 指数に関する関数

// x の y 乗を求める.
ll intpow(ll x, ll y){
    ll a = 1;
    while (y){
        if (y & 1) { a *= x; }
        x *= x;
        y >>= 1;
    }
    return a;
}

ll pow(ll x, ll y) { return intpow(x, y); }

// x の y 乗を z で割った余りを求める.
template<typename T, integral U>
T modpow(T x, U y, T z) {
    T a = 1;
    while (y) {
        if (y & 1) { (a *= x) %= z; }

        (x *= x) %= z;
        y >>= 1;
    }

    return a;
}

template<typename T>
T sum(const vector<T> &X) {
    T y = T(0);
    for (auto &&x: X) { y += x; }
    return y;
}

template<typename T>
T gcd(const T x, const T y) {
    return y == 0 ? x : gcd(y, x % y);
}

// a x + b y = gcd(a, b) を満たす整数の組 (a, b) に対して, (x, y, gcd(a, b)) を求める.
template<integral T>
tuple<T, T, T> Extended_Euclid(T a, T b) {
    T s = 1, t = 0, u = 0, v = 1;
    while (b) {
        auto [q, r] = divmod(a, b);
        a = b;
        b = r;
        tie(s, t) = make_pair(t, s - q * t);
        tie(u, v) = make_pair(v, u - q * v);
    }

    return make_tuple(s, u, a);
}

// floor(sqrt(N)) を求める (N < 0 のときは, 0 とする).
ll isqrt(const ll &N) { 
    if (N <= 0) { return 0; }

    ll x = sqrtl(N);
    while ((x + 1) * (x + 1) <= N) { x++; }
    while (x * x > N) { x--; }

    return x;
}

// floor(sqrt(N)) を求める (N < 0 のときは, 0 とする).
ll floor_sqrt(const ll &N) { return isqrt(N); }

// ceil(sqrt(N)) を求める (N < 0 のときは, 0 とする).
ll ceil_sqrt(const ll &N) {
    ll x = isqrt(N);
    return x * x == N ? x : x + 1;
}
#line 64 "template/template.hpp"

// inout
#line 1 "template/inout.hpp"
// 入出力
template<class... T>
void input(T&... a){ (cin >> ... >> a); }

void print(){ cout << "\n"; }

template<class T, class... Ts>
void print(const T& a, const Ts&... b){
    cout << a;
    (cout << ... << (cout << " ", b));
    cout << "\n";
}

template<typename T, typename U>
istream &operator>>(istream &is, pair<T, U> &P){
    is >> P.first >> P.second;
    return is;
}

template<typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &P){
    os << P.first << " " << P.second;
    return os;
}

template<typename T>
vector<T> vector_input(int N, int index){
    vector<T> X(N+index);
    for (int i=index; i<index+N; i++) cin >> X[i];
    return X;
}

template<typename T>
istream &operator>>(istream &is, vector<T> &X){
    for (auto &x: X) { is >> x; }
    return is;
}

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

template<typename T>
ostream &operator<<(ostream &os, const unordered_set<T> &S){
    int i = 0;
    for (T a: S) {os << (i ? " ": "") << a; i++;}
    return os;
}

template<typename T>
ostream &operator<<(ostream &os, const set<T> &S){
    int i = 0;
    for (T a: S) { os << (i ? " ": "") << a; i++; }
    return os;
}

template<typename T>
ostream &operator<<(ostream &os, const unordered_multiset<T> &S){
    int i = 0;
    for (T a: S) { os << (i ? " ": "") << a; i++; }
    return os;
}

template<typename T>
ostream &operator<<(ostream &os, const multiset<T> &S){
    int i = 0;
    for (T a: S) { os << (i ? " ": "") << a; i++; }
    return os;
}

template<typename T>
std::vector<T> input_vector(size_t n, size_t offset = 0) {
    std::vector<T> res;
    // 最初に必要な全容量を確保(再確保を防ぐ)
    res.reserve(n + offset);
    // offset 分をデフォルト値で埋める(特別 indexed 用)
    res.assign(offset, T());
    
    for (size_t i = 0; i < n; ++i) {
        T el;
        if (!(std::cin >> el)) break;
        res.push_back(std::move(el));
    }
    return res;
}
#line 67 "template/template.hpp"

// macro
#line 2 "template/macro.hpp"

// マクロの定義
#define all(x) x.begin(), x.end()
#define len(x) ll(x.size())
#define elif else if
#define unless(cond) if (!(cond))
#define until(cond) while (!(cond))
#define loop while (true)

// オーバーロードマクロ
#define overload2(_1, _2, name, ...) name
#define overload3(_1, _2, _3, name, ...) name
#define overload4(_1, _2, _3, _4, name, ...) name
#define overload5(_1, _2, _3, _4, _5, name, ...) name

// 繰り返し系
#define rep1(n) for (ll i = 0; i < n; i++)
#define rep2(i, n) for (ll i = 0; i < n; i++)
#define rep3(i, a, b) for (ll i = a; i < b; i++)
#define rep4(i, a, b, c) for (ll i = a; i < b; i += c)
#define rep(...) overload4(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)

#define foreach1(x, a) for (auto &&x: a)
#define foreach2(x, y, a) for (auto &&[x, y]: a)
#define foreach3(x, y, z, a) for (auto &&[x, y, z]: a)
#define foreach4(x, y, z, w, a) for (auto &&[x, y, z, w]: a)
#define foreach(...) overload5(__VA_ARGS__, foreach4, foreach3, foreach2, foreach1)(__VA_ARGS__)
#line 70 "template/template.hpp"

// bitop
#line 2 "template/bitop.hpp"

// 非負整数 x の bit legnth を求める.
ll bit_length(ll x) {
    if (x == 0) { return 0; }
    return (sizeof(long) * CHAR_BIT) - __builtin_clzll(x);
}

// 非負整数 x の popcount を求める.
ll popcount(ll x) { return __builtin_popcountll(x); }

// 正の整数 x に対して, floor(log2(x)) を求める.
ll floor_log2(ll x) { return bit_length(x) - 1; }

// 正の整数 x に対して, ceil(log2(x)) を求める.
ll ceil_log2(ll x) { return bit_length(x - 1); }

// x の第 k ビットを取得する
int get_bit(ll x, int k) { return (x >> k) & 1; }

// x のビット列を取得する.
// k はビット列の長さとする.
vector<int> get_bits(ll x, int k) {
    vector<int> bits(k);
    rep(i, k) {
        bits[i] = x & 1;
        x >>= 1;
    }

    return bits;
}

// x のビット列を取得する.
vector<int> get_bits(ll x) { return get_bits(x, bit_length(x)); }

// x に立っているなんかしらのビットの番号を出力する.
ll lowest_bit(const ll x) { return floor_log2(x & (-x)); }
#line 73 "template/template.hpp"

// exception
#line 2 "template/exception.hpp"

class NotExist: public exception {
    private:
    string message;

    public:
    NotExist() : message("求めようとしていたものは存在しません.") {}

    const char* what() const noexcept override {
        return message.c_str();
    }
};
#line 2 "template/enumerable.hpp"

#line 11 "template/enumerable.hpp"
#include <stdexcept>
#line 13 "template/enumerable.hpp"

namespace enumerable {
    /// @brief コンテナの各要素に関数を適用し、その結果を新しい `std::vector` として返す。
    ///
    /// Ruby の `Enumerable#collect` (または `map`) に相当します。C++の `std::transform` に似ていますが、常に出力として新しい `std::vector` を生成して返す点が異なります。
    /// @tparam Container イテレート可能なコンテナの型 (e.g., std::vector<T>)。
    /// @tparam Func 各要素に適用する関数の型。
    /// @param container 対象のコンテナ。
    /// @param func 各要素に適用する関数オブジェクト (ラムダ式など)。
    /// @return 関数の適用結果を格納した新しい `std::vector`。
    template <typename Container, typename Func>
    auto collect(const Container& container, const Func& func) {
        using ResultType = std::invoke_result_t<Func, typename Container::const_reference>;
        std::vector<ResultType> result;
        if constexpr (requires { std::size(container); }) {
            result.reserve(std::size(container));
        }
        for (const auto& element : container) {
            result.push_back(std::invoke(func, element));
        }
        return result;
    }

    /// @brief コンテナの各要素に対して述語関数を適用し、真を返した要素のみを格納した新しい `std::vector` を返す。
    ///
    /// Ruby の `Enumerable#select` や `Enumerable#filter` に相当します。
    /// @tparam Container イテレート可能なコンテナの型。
    /// @tparam Pred 各要素に対する条件判定を行う関数の型。
    /// @param container 対象のコンテナ。
    /// @param pred 各要素に対して真偽値を返す関数オブジェクト。
    /// @return 条件を満たす要素を格納した新しい `std::vector`。
    template <typename Container, typename Pred>
    auto select(const Container& container, const Pred& pred) {
        using T = std::decay_t<typename Container::const_reference>;
        std::vector<T> result;
        for (const auto& element : container) {
            if (std::invoke(pred, element)) {
                result.push_back(element);
            }
        }
        return result;
    }

    /// @brief コンテナの各要素に対して述語関数を適用し、偽を返した要素のみを格納した新しい `std::vector` を返す。
    ///
    /// Ruby の `Enumerable#reject` に相当します。
    /// @tparam Container イテレート可能なコンテナの型。
    /// @tparam Pred 各要素に対する条件判定を行う関数の型。
    /// @param container 対象のコンテナ。
    /// @param pred 各要素に対して真偽値を返す関数オブジェクト。
    /// @return 条件を満たさない(偽となる)要素を格納した新しい `std::vector`。
    template <typename Container, typename Pred>
    auto reject(const Container& container, const Pred& pred) {
        using T = std::decay_t<typename Container::const_reference>;
        std::vector<T> result;
        for (const auto& element : container) {
            if (!std::invoke(pred, element)) {
                result.push_back(element);
            }
        }
        return result;
    }

    /// @brief コンテナの要素を畳み込む。
    ///
    /// Ruby の `Enumerable#inject` (または `reduce`) に相当します。
    /// @param init 初期値。
    /// @param func 畳み込み関数 (accum, element) -> accum。
    template <typename Container, typename T, typename Func>
    auto inject(const Container& container, T init, Func func) {
        for (const auto& element : container) {
            init = std::invoke(func, init, element);
        }
        return init;
    }

    /// @brief コンテナの要素を畳み込む(初期値なし)。
    ///
    /// Ruby の `Enumerable#inject` (または `reduce`) に相当します。
    /// コンテナが空の場合は例外を投げます。
    template <typename Container, typename Func>
    auto inject(const Container& container, Func func) {
        auto it = std::begin(container);
        auto end = std::end(container);
        if (it == end) throw std::runtime_error("enumerable::inject: container is empty");
        // 値のコピーを作成してアキュムレータとする
        auto result = *it; 
        ++it;
        for (; it != end; ++it) {
            result = std::invoke(func, result, *it);
        }
        return result;
    }

    /// @brief すべての要素が条件を満たすか判定する。
    /// Ruby の `Enumerable#all?` に相当します。
    template <typename Container, typename Pred>
    bool all_of(const Container& container, Pred pred) {
        return std::all_of(std::begin(container), std::end(container), pred);
    }

    /// @brief いずれかの要素が条件を満たすか判定する。
    /// Ruby の `Enumerable#any?` に相当します。
    template <typename Container, typename Pred>
    bool any_of(const Container& container, Pred pred) {
        return std::any_of(std::begin(container), std::end(container), pred);
    }

    /// @brief すべての要素が条件を満たさないか判定する。
    /// Ruby の `Enumerable#none?` に相当します。
    template <typename Container, typename Pred>
    bool none_of(const Container& container, Pred pred) {
        return std::none_of(std::begin(container), std::end(container), pred);
    }

    /// @brief 指定した値が含まれているか判定する。
    /// Ruby の `Enumerable#include?` (または `member?`) に相当します。
    template <typename Container, typename T>
    bool include(const Container& container, const T& val) {
        return std::find(std::begin(container), std::end(container), val) != std::end(container);
    }

    /// @brief 条件を満たす最初の要素を返す。
    /// Ruby の `Enumerable#find` (または `detect`) に相当します。
    /// 見つからない場合は std::nullopt を返します。
    template <typename Container, typename Pred>
    auto find(const Container& container, Pred pred) -> std::optional<typename Container::value_type> {
        auto it = std::find_if(std::begin(container), std::end(container), pred);
        if (it != std::end(container)) return *it;
        return std::nullopt;
    }

    /// @brief 条件を満たす最初の要素のインデックスを返す。
    /// Ruby の `Enumerable#find_index` に相当します。
    /// 見つからない場合は std::nullopt を返します。
    template <typename Container, typename Pred>
    std::optional<size_t> find_index(const Container& container, Pred pred) {
        auto it = std::find_if(std::begin(container), std::end(container), pred);
        if (it != std::end(container)) return std::distance(std::begin(container), it);
        return std::nullopt;
    }

    /// @brief 条件を満たす要素の数を返す。
    /// Ruby の `Enumerable#count` (ブロック付き) に相当します。
    template <typename Container, typename Pred>
    size_t count(const Container& container, Pred pred) {
        return std::count_if(std::begin(container), std::end(container), pred);
    }

    /// @brief 条件を満たす要素と満たさない要素に分割する。
    /// Ruby の `Enumerable#partition` に相当します。
    /// @return {満たす要素のリスト, 満たさない要素のリスト} のペア
    template <typename Container, typename Pred>
    auto partition(const Container& container, Pred pred) {
        using T = typename Container::value_type;
        std::vector<T> true_list, false_list;
        for (const auto& element : container) {
            if (std::invoke(pred, element)) {
                true_list.push_back(element);
            } else {
                false_list.push_back(element);
            }
        }
        return std::make_pair(true_list, false_list);
    }

    /// @brief ブロックの評価結果ごとにグループ化する。
    /// Ruby の `Enumerable#group_by` に相当します。
    /// @return キー -> 要素リスト のマップ
    template <typename Container, typename Func>
    auto group_by(const Container& container, Func func) {
        using T = typename Container::value_type;
        using Key = std::invoke_result_t<Func, typename Container::const_reference>;
        std::map<Key, std::vector<T>> result;
        for (const auto& element : container) {
            result[std::invoke(func, element)].push_back(element);
        }
        return result;
    }

    /// @brief ブロックの評価結果を使ってソートする。
    /// Ruby の `Enumerable#sort_by` に相当します。
    template <typename Container, typename Func>
    auto sort_by(const Container& container, Func func) {
        using T = typename Container::value_type;
        using Key = std::decay_t<std::invoke_result_t<Func, typename Container::const_reference>>;
        
        std::vector<std::pair<Key, T>> pairs;
        if constexpr (requires { std::size(container); }) {
            pairs.reserve(std::size(container));
        }
        for (const auto& element : container) {
            pairs.emplace_back(std::invoke(func, element), element);
        }

        std::sort(pairs.begin(), pairs.end(), [](const auto& a, const auto& b) {
            return a.first < b.first;
        });

        std::vector<T> result;
        result.reserve(pairs.size());
        for (const auto& p : pairs) {
            result.push_back(p.second);
        }
        return result;
    }

    /// @brief 重複を取り除いた新しいリストを返す(出現順を保持)。
    /// Ruby の `Enumerable#uniq` に相当します。
    template <typename Container>
    auto uniq(const Container& container) {
        using T = typename Container::value_type;
        std::vector<T> result;
        std::set<T> seen;
        for (const auto& element : container) {
            if (seen.find(element) == seen.end()) {
                seen.insert(element);
                result.push_back(element);
            }
        }
        return result;
    }

} // namespace enumerable
#line 2 "Counting/Combination_Calculator.hpp"

#line 4 "Counting/Combination_Calculator.hpp"

template<typename mint>
class Combination_Calculator {
    private:
    vector<mint> _fact, _fact_inv;

    void resize(const int m) {
        if (m < _fact.size()) { return; }

        int current_size = _fact.size();
        int next_size = min(max(2 * current_size, m + 1), mint::mod());

        _fact.resize(next_size);
        _fact_inv.resize(next_size);

        for (int k = current_size; k < next_size; k++) {
            _fact[k] = k * _fact[k - 1];
        }

        _fact_inv.back() = _fact.back().inverse();

        for (int k = next_size - 2; k >= current_size; --k) {
            _fact_inv[k] = (k + 1) * _fact_inv[k + 1];
        }
    }

    public:
    /**
     * @brief コンストラクタ: 初期サイズnまで階乗・逆階乗を計算する
     * @param n 初期計算の上限
     */
    Combination_Calculator(const int n) {
        _fact.emplace_back(1); _fact.emplace_back(1);
        _fact_inv.emplace_back(1); _fact_inv.emplace_back(1);

        resize(n);
    }

    Combination_Calculator(): Combination_Calculator(0) {}

    /**
     * @brief k! を取得
     */
    mint fact(const int k) {
        resize(k);
        return _fact[k];
    }

    /**
     * @brief (k!)^(-1) を取得
     */
    mint fact_inv(const int k) {
        resize(k);
        return _fact_inv[k];
    }

    /**
     * @brief k の逆元 k^(-1) を求める
     * @param k 逆元を求めたい数
     */
    mint inv(const int k) {
        if (k <= 0) { return 0; }

        resize(k);
        return _fact_inv[k] * _fact[k - 1];
    }

    /**
     * @brief 組み合わせ nCk を計算する
     */
    mint nCr(const int n, const int r) {
        if (!(0 <= r && r <= n)) { return 0; }
        resize(n);
        return _fact[n] * _fact_inv[r] * _fact_inv[n - r];
    }

    /**
     * @brief 順列 nPk を計算する
     */
    mint nPr(const int n, const int r) {
        if (!(0 <= r && r <= n)) { return 0; }
        resize(n);
        return _fact[n] * _fact_inv[n - r];
    }

    /**
     * @brief 重複組合せ nHk を計算する
     */
    mint nHr(const int n, const int r) {
        if (n == 0 && r == 0) { return 1; }

        return nCr(n + r - 1, r);
    }

    /**
     * @brief 多項係数 (k_sum)! / (k1! * k2! * ...) を計算する
     */
    mint multinomial_coefficient(const vector<int> &ks) {
        int k_sum = 0;
        mint lower = 1;
        for (int k: ks) {
            k_sum += k;
            lower *= _fact_inv[k];
        }

        resize(k_sum);

        mint upper = _fact[k_sum];

        return upper * lower;
    }

    mint catalan(const int n) {
        if (n < 0) { return 0; }
        resize(2 * n);
        return _fact[2 * n] * _fact_inv[n + 1] * _fact_inv[n];
    }
};
#line 6 "Math/Lagrange_Interpolation.hpp"

/**
 * @brief ラグランジュ補間を用いた評価点の値の計算 (O(N^2))
 * @details 与えられた n 個の点 (x[i], y[i]) を通る n-1 次以下の多項式 P に対し、P(X) を求める。
 * @tparam F 体を表す型 (ModInt 等)
 * @param x 点の x 座標のリスト (すべて異なる必要がある)
 * @param y 点の y 座標のリスト
 * @param X 評価点
 * @return F P(X) の値
 */
template<typename F>
F Lagrange_Interpolation_Point(const vector<F> &x, const vector<F> &y, F X) {
    assert(x.size() == y.size());
    int n = (int)x.size();

    // 分子の累積積を前計算 O(N)
    vector<F> pre(n + 1, F(1)), suf(n + 1, F(1));
    for (int i = 0; i < n; ++i) pre[i + 1] = pre[i] * (X - x[i]);
    for (int i = n - 1; i >= 0; --i) suf[i] = suf[i + 1] * (X - x[i]);

    F Y = F(0);
    for (int i = 0; i < n; ++i) {
        // 分母の積を計算
        F den = F(1);
        for (int j = 0; j < n; ++j) {
            if (i == j) continue;

            den *= (x[i] - x[j]);
        }

        Y += y[i] * pre[i] * suf[i + 1] / den;
    }

    return Y;
}

/**
 * @brief ラグランジュ補間を用いた評価点の値の計算 (O(N^2))
 * @details points[i] = (x_i, y_i) を通る n-1 次以下の多項式 P に対し、P(X) を求める。
 * @tparam F 体を表す型
 * @param points 点 (x, y) のリスト
 * @param X 評価点
 * @return F P(X) の値
 */
template<typename F>
F Lagrange_Interpolation_Point(const vector<pair<F, F>> &points, F X) {
    auto x = enumerable::collect(points, [](const auto &p) { return p.first; });
    auto y = enumerable::collect(points, [](const auto &p) { return p.second; });
    return Lagrange_Interpolation_Point(x, y, X);
}

/**
 * @brief ラグランジュ補間を用いた多項式の係数の決定 (O(N^2))
 * @details 与えられた n 個の点 (x[i], y[i]) を通る n-1 次以下の多項式 P(x) = \sum res[i] * x^i を求める。
 * @tparam F 体を表す型
 * @param x 点の x 座標のリスト (すべて異なる必要がある)
 * @param y 点の y 座標のリスト
 * @return vector<F> 多項式の係数リスト res (res[i] は x^i の係数)
 */
template<typename F>
vector<F> Lagrange_Interpolation_Polynomial(const vector<F> &x, const vector<F> &y) {
    assert(x.size() == y.size());
    int n = (int)x.size();
    if (n == 0) return {};

    // Section I: m(x) = \prod (x - xs[i]) を計算
    vector<F> m(n + 1, 0);
    m[0] = 1;
    for (int i = 0; i < n; ++i) {
        for (int j = i; j >= 0; --j) {
            m[j + 1] += m[j];
            m[j] *= -x[i];
        }
    }

    // Section II: m の導関数 m' を求める.
    vector<F> m_diff(n);
    for (int i = 1; i <= n; ++i) {
        m_diff[i - 1] = F(i) * m[i];
    }

    // Section III: f を求める.
    vector<F> res(n, 0);
    for (int i = 0; i < n; ++i) {
        // Evaluate m'(x[i]) using Horner's method
        F val_diff = 0;
        for (int j = n - 1; j >= 0; --j) {
            val_diff = val_diff * x[i] + m_diff[j];
        }

        F weight = y[i] / val_diff;

        // Compute Q_i(x) = m(x) / (x - x[i]) and add weight * Q_i(x) to res
        F q = m[n];
        for (int j = n - 1; j >= 0; --j) {
            res[j] += weight * q;
            q = m[j] + x[i] * q;
        }
    }
    return res;
}

/**
 * @brief ラグランジュ補間を用いた多項式の係数の決定 (O(N^2))
 * @details points[i] = (x_i, y_i) を通る n-1 次以下の多項式 P(x) = \sum res[i] * x^i を求める。
 * @tparam F 体を表す型
 * @param points 点 (x, y) のリスト
 * @return vector<F> 多項式の係数リスト res (res[i] は x^i の係数)
 */
template<typename F>
vector<F> Lagrange_Interpolation_Polynomial(const vector<pair<F, F>> &points) {
    auto x = enumerable::collect(points, [](const auto &p) { return p.first; });
    auto y = enumerable::collect(points, [](const auto &p) { return p.second; });
    return Lagrange_Interpolation_Polynomial(x, y);
}

/**
 * @brief 等差数列上の点におけるラグランジュ補間 (O(N))
 * @details 多項式 P(a*i + b) = y[i] (0 <= i < |y|) を満たす P(s) を求める。
 * @tparam F 体を表す型 (ModInt 等)
 * @param a 等差数列の公差
 * @param b 等差数列の初項
 * @param y 各点における多項式の値のリスト
 * @param s 評価点
 * @return F P(s) の値
 */
template<typename F>
F Lagrange_Interpolation_Point_Arithmetic(const F a, const F b, const vector<F> &y, const F s) {
    int n = (int)y.size();
    if (n == 0) return F(0);
    if (n == 1) return y[0];
    int d = n - 1;

    // 階乗の逆元を計算
    vector<F> inv_fact(n);
    {
        F f = 1;
        for (int i = 2; i <= d; ++i) f *= i;
        inv_fact[d] = F(1) / f;
        for (int i = d; i >= 1; --i) inv_fact[i - 1] = inv_fact[i] * i;
    }

    // 右からの累積積を計算
    vector<F> suffix(n);
    {
        F cur_x = b + a * d;
        for (int i = d; i >= 0; --i) {
            suffix[i] = (i == d ? s - cur_x : suffix[i + 1] * (s - cur_x));
            cur_x -= a;
        }
    }

    // coef = (-a)^{-d}
    F coef = (a == F(1)) ? ((d & 1) ? F(-1) : F(1)) : pow(-a, -d);

    F t = 0;
    F running_prefix = 1;
    F cur_x = b;
    for (int i = 0; i < n; ++i) {
        F suf = (i == d) ? 1 : suffix[i + 1];

        F alpha = running_prefix * suf * inv_fact[i] * inv_fact[d - i];
        if (is_odd(i)) t -= y[i] * alpha;
        else t += y[i] * alpha;

        running_prefix *= (s - cur_x);
        cur_x += a;
    }

    return coef * t;
}

/**
 * @brief 連続する整数点におけるラグランジュ補間 (O(N))
 * @details 多項式 P(i) = y[i] (0 <= i < |y|) を満たす P(s) を求める。
 * @tparam F 体を表す型 (ModInt 等)
 * @param y 各点における多項式の値のリスト (x = 0, 1, ..., |y|-1)
 * @param s 評価点
 * @return F P(s) の値
 */
template<typename F>
F Lagrange_Interpolation_Point_Arithmetic(const vector<F> &y, const F s) {
    return Lagrange_Interpolation_Point_Arithmetic<F>(1, 0, y, s);
}
Back to top page