結果

問題 No.117 組み合わせの数
ユーザー tubo28tubo28
提出日時 2017-01-27 18:27:49
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 79 ms / 5,000 ms
コード長 2,248 bytes
コンパイル時間 1,512 ms
コンパイル使用メモリ 166,088 KB
実行使用メモリ 34,344 KB
最終ジャッジ日時 2023-08-25 03:40:20
合計ジャッジ時間 2,173 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 79 ms
34,344 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <vector>
#include <utility>
#include <tuple>

template<typename Int, Int MOD>
struct comb_util {
    int sz;
    std::vector<Int> mfact, minv_fact;
    comb_util(int N) : sz(N + 1), mfact(sz), minv_fact(sz) {
        mfact[0] = 1;
        for (int i = 1; i <= sz; i++) mfact[i] = mfact[i - 1] * i % MOD;
        minv_fact[sz] = inv(mfact[sz]);
        for (int i = sz - 1; i >= 0; i--) minv_fact[i] = minv_fact[i + 1] * (i + 1) % MOD;
    }

    // res = first * p^second
    std::pair<Int, Int> fact_willson(Int n) const {
        Int e = 0;
        if (n <= sz) return std::make_pair(mfact[n], 0);
        Int res;
        std::tie(res, e) = fact_willson(n / MOD);
        e += n / MOD;
        if ((n / MOD) % 2 != 0) res = MOD - res;
        return std::make_pair(res * mfact[n % MOD] % MOD, e);
    }

    Int fact(Int n) const { return mfact[n]; }

    Int inv(Int n) const {
        return pow(n, MOD - 2);
    }

    Int pow(Int n, Int a) const {
        Int res = 1, exp = n;
        for(; a; a /= 2) {
            if (a & 1) res = res * exp % MOD;
            exp = exp * exp % MOD;
        }
        return res;
    }

    Int perm(Int n, Int r) {
        if (r < 0 || n < r) return 0;
        else return mfact[n] * minv_fact[n - r] % MOD;
    }

    Int binom_lucus(Int n, Int r) const {
        if (n < 0 || r < 0 || n < r) return 0;
        assert(n <= sz);
        if (n >= MOD) return binom(n % MOD, r % MOD) * binom(n / MOD, r / MOD);
        else return r > n ? 0 : mfact[n] * minv_fact[n - r] * minv_fact[r];
    }

    Int binom(Int n, Int r) const {
        if (n < 0 || r < 0 || n < r) return 0;
        return mfact[n] * minv_fact[r] % MOD * minv_fact[n - r] % MOD;
    }

    Int homo(Int n, Int r) const {
        if (n < 0 || r < 0) return 0;
        return r == 0 ? 1 : binom(n + r - 1, r);
    }
};
using comb = comb_util<long long, 1000000007>;

#include <bits/stdc++.h>

int main(){
    int T;
    comb cm(2000010);

    scanf("%d\n", &T);
    for(int i=0;i<T;i++){
        char c; int N, K;
        scanf("%c(%d,%d)\n",&c,&N,&K);
        int ans = -1;
        if(c=='C') ans = cm.binom(N,K);
        if(c=='P') ans = cm.perm(N,K);
        if(c=='H') ans = cm.homo(N,K);
        printf("%d\n", ans);
    }
}
0