結果
問題 | No.117 組み合わせの数 |
ユーザー | h173309 |
提出日時 | 2020-05-10 04:24:42 |
言語 | Python3 (3.12.2 + numpy 1.26.4 + scipy 1.12.0) |
結果 |
TLE
|
実行時間 | - |
コード長 | 2,335 bytes |
コンパイル時間 | 174 ms |
コンパイル使用メモリ | 12,928 KB |
実行使用メモリ | 128,512 KB |
最終ジャッジ日時 | 2024-07-06 15:34:49 |
合計ジャッジ時間 | 11,183 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ソースコード
class Factorial(): def __init__(self, mod=10**9 + 7): self.mod = mod self._factorial = [1] self._size = 1 self._factorial_inv = [1] self._size_inv = 1 def __call__(self, n): '''n! % mod ''' return self.fact(n) def fact(self, n): '''n! % mod ''' if n >= self.mod: return 0 self.make(n) return self._factorial[n] def fact_inv(self, n): '''n!^-1 % mod ''' if n >= self.mod: raise ValueError('Modinv is not exist! arg={}'.format(n)) self.make_inv(n) return self._factorial_inv[n] def comb(self, n, r): ''' nCr % mod ''' if r > n: return 0 t = self.fact_inv(n-r)*self.fact_inv(r) % self.mod return self(n)*t % self.mod def comb_with_repetition(self, n, r): ''' nHr % mod ''' t = self.fact_inv(n-1)*self.fact_inv(r) % self.mod return self(n+r-1)*t % self.mod def perm(self, n, r): ''' nPr % mod ''' if r > n: return 0 return self(n)*self.fact_inv(n-r) % self.mod def modinv(self, n): ''' n^-1 (mod p)''' n %= self.mod if n == 0: raise ValueError('Modinv is not exist! arg={}'.format(n)) ## TODO better than extend_gcd return pow(n, self.mod-2, self.mod) def make(self, n): if n >= self.mod: n = self.mod if self._size < n+1: for i in range(self._size, n+1): self._factorial.append(self._factorial[i-1]*i % self.mod) self._size = n+1 def make_inv(self, n): if n >= self.mod: n = self.mod self.make(n) if self._size_inv < n+1: for i in range(self._size_inv, n+1): self._factorial_inv.append(self.modinv(self._factorial[i])) self._size_inv = n+1 fact = Factorial() comb = fact.comb perm = fact.perm comb_with_repetition = fact.comb_with_repetition for _ in range(int(input())): q, n, r = input().replace('(', ',').replace(')', '').split(',') n, r = map(int, (n, r)) if q == 'C': print(comb(n, r)) elif q == 'P': print(perm(n, r)) else: print(comb_with_repetition(n, r))