結果
| 問題 |
No.117 組み合わせの数
|
| ユーザー |
tubo28
|
| 提出日時 | 2017-01-27 18:23:20 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 263 ms / 5,000 ms |
| コード長 | 2,866 bytes |
| コンパイル時間 | 1,686 ms |
| コンパイル使用メモリ | 169,712 KB |
| 実行使用メモリ | 50,048 KB |
| 最終ジャッジ日時 | 2024-12-23 15:48:39 |
| 合計ジャッジ時間 | 2,536 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 1 |
ソースコード
#include <vector>
#include <utility>
#include <tuple>
#include <iostream>
using namespace std;
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 {
// Wilson の定理
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) return (MOD - res) * mfact[n % MOD] % MOD;
// else return res * mfact[n % MOD] % 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 res;
// tie(std::ignore, res) = extgcd(n, MOD);
// return (res + MOD) % MOD;
}
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;
}
// std::pair<Int, Int> extgcd(Int a, Int b) const {
// if(b == 0){
// return std::make_pair(1, 0);
// } else {
// Int x, y;
// std::tie(y, x) = extgcd(b, a%b);
// return std::make_pair(x, y - (a / b) * x);
// }
// }
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(3000010);
while(cin >> T){
for(int i=0;i<T;i++){
char c; int N, K;
scanf("\n%c(%d,%d)",&c,&N,&K);
if(c=='C') cout << cm.binom(N,K);
if(c=='P') cout << cm.perm(N,K);
if(c=='H') cout << cm.homo(N,K);
cout << endl;
}
}
}
tubo28