結果

問題 No.117 組み合わせの数
ユーザー zawakasuzawakasu
提出日時 2022-12-17 09:35:19
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 243 ms / 5,000 ms
コード長 2,234 bytes
コンパイル時間 567 ms
コンパイル使用メモリ 76,128 KB
実行使用メモリ 34,420 KB
最終ジャッジ日時 2024-04-28 05:34:09
合計ジャッジ時間 1,373 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <vector>
#include <cassert>

namespace zawa {

template <long long mod>
class mod_conbinations {
private:
    std::vector<long long> facs, inv_facs;

public:
    mod_conbinations(std::size_t n) : facs(2 * n + 1, 1LL), inv_facs(2 * n + 1) {
        for (std::size_t i = 0 ; i + 1 < facs.size() ; i++) {
            facs[i + 1] = facs[i] * (i + 1);
            facs[i + 1] %= mod;
        }
        long long base = facs.back();
        long long inv = 1LL;
        long long p = mod - 2;
        while (p > 0) {
            if (p & 1) {
                inv *= base;
                inv %= mod;
            }
            base = (base * base) % mod;
            p >>= 1;
        }
        inv_facs.back() = inv;
        for (int i = (int)facs.size() - 1 ; i - 1 >= 0 ; i--) {
            inv_facs[i - 1] = inv_facs[i] * i;
            inv_facs[i - 1] %= mod;
        }
    }

    long long P(std::size_t n, std::size_t r) {
        if (r > n) {
            return 0LL;
        }
        return (facs[n] * inv_facs[(n - r)]) % mod;
    }

    long long C(std::size_t n, std::size_t r) {
        if (r > n) {
            return 0LL;
        }
        return (P(n, r) * inv_facs[r]) % mod;
    }

    long long H(std::size_t n, std::size_t r) {
        if (n == 0 and r == 0) {
            return 1LL;
        }
        if (r > n + r - 1) {
            return 0LL;
        }
        return C(n + r - 1, r);
    }
};

} // namespace zawa

#include <iostream>

int read() {
    int res = 0;
    while (1) {
        char d; std::cin >> d;
        if ('0' <= d and d <= '9') {
            res *= 10;
            res += (d - '0');
        }
        else {
            break;
        }
    }
    return res;
}

int main() {
    zawa::mod_conbinations<1000000007LL> mc(1000000);
    int t; std::cin >> t;
    for (int _ = 0 ; _ < t ; _++) {
        char c; std::cin >> c;
        char f; std::cin >> f;
        assert(f == '(');
        int n = read();
        int r = read();
        if (c == 'C') {
            std::cout << mc.C(n, r) << std::endl;
        }
        if (c == 'P') {
            std::cout << mc.P(n, r) << std::endl;
        }
        if (c == 'H') {
            std::cout << mc.H(n, r) << std::endl;
        }
    } 
}
0