結果

問題 No.665 Bernoulli Bernoulli
ユーザー kimiyuki
提出日時 2018-03-09 23:46:01
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 825 ms / 2,000 ms
コード長 2,082 bytes
コンパイル時間 2,173 ms
コンパイル使用メモリ 197,484 KB
最終ジャッジ日時 2025-01-05 09:11:29
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 15
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; (i) < int(n); ++ (i))
using ll = long long;
using namespace std;

ll powmod(ll x, ll y, ll m) {
    assert (0 <= x and x < m);
    assert (0 <= y);
    ll z = 1;
    for (ll i = 1; i <= y; i <<= 1) {
        if (y & i) z = z * x % m;
        x = x * x % m;
    }
    return z;
}
ll modinv(ll x, ll p) {
    assert (x % p != 0);
    return powmod(x, p - 2, p);
}

template <int32_t MOD>
int32_t fact(int n) {
    static vector<int32_t> memo(1, 1);
    while (n >= memo.size()) {
        memo.push_back(memo.back() *(int64_t) memo.size() % MOD);
    }
    return memo[n];
}
template <int32_t PRIME>
int32_t inv_fact(int n) {
    static vector<int32_t> memo(1, 1);
    while (n >= memo.size()) {
        memo.push_back(memo.back() *(int64_t) modinv(memo.size(), PRIME) % PRIME);
    }
    return memo[n];
}
template <int MOD>
int choose(int n, int r) {
    if (n < r) return 0;
    return fact<MOD>(n) *(ll) inv_fact<MOD>(n - r) % MOD *(ll) inv_fact<MOD>(r) % MOD;
}

/**
 * @tparam MOD must be a prime
 * @note O(n^2)
 * @see https://ja.wikipedia.org/wiki/%E3%83%99%E3%83%AB%E3%83%8C%E3%83%BC%E3%82%A4%E6%95%B0
 */
template <int MOD>
int bernoulli_number(int i) {
    static vector<int> dp(1, 1);
    while (dp.size() <= i) {
        int n = dp.size();
        ll acc = 0;
        REP (k, n) {
            acc += choose<MOD>(n + 1, k) *(ll) dp[k] % MOD;
        }
        acc %= MOD;
        (acc *= modinv(n + 1, MOD)) %= MOD;
        acc = (acc == 0 ? 0 : MOD - acc);
        dp.push_back(acc);
    }
    return dp[i];
}

/**
 * @brief 0^k + 1^k + 2^k + ... + (n - 1)^k
 */
template <int MOD>
int sum_of_pow(ll n, int k) {
    ll acc = 0;
    REP (j, k + 1) {
        acc += choose<MOD>(k + 1, j) *(ll) bernoulli_number<MOD>(j) % MOD *(ll) powmod(n % MOD, k - j + 1, MOD) % MOD;
    }
    acc %= MOD;
    (acc *= modinv(k + 1, MOD)) %= MOD;
    return acc;
}


constexpr int MOD = 1e9 + 7;
int main() {
    ll n; int k; cin >> n >> k;
    int result = sum_of_pow<MOD>(n + 1, k);
    cout << result << endl;
    return 0;
}
0