結果
問題 | No.117 組み合わせの数 |
ユーザー | h173309 |
提出日時 | 2020-05-06 09:28:19 |
言語 | Python3 (3.12.2 + numpy 1.26.4 + scipy 1.12.0) |
結果 |
RE
|
実行時間 | - |
コード長 | 2,386 bytes |
コンパイル時間 | 156 ms |
コンパイル使用メモリ | 12,928 KB |
実行使用メモリ | 10,880 KB |
最終ジャッジ日時 | 2024-06-28 03:34:20 |
合計ジャッジ時間 | 720 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
ソースコード
class Factorial(): def __init__(self, mod=10**9 + 7): self.mod = mod self._factorial = [1] self._size = 1 def __call__(self, n): '''n! % mod ''' if n >= self.mod: return 0 self.make(n) return self._factorial[n] 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[-1]*i % self.mod) self._size = n+1 class Modinv(): def __init__(self, mod=10**9 + 7): self.mod = mod self._modinv = [1] self._size = 1 def __call__(self, n): '''n^-1 % mod ''' n %= self.mod self.make(n) return self._modinv[n] def make(self, n): if self._size < n+1: for i in range(self._size, n+1): self._modinv.append(self.inverse(i)) self._size = n+1 @staticmethod def xgcd(a, b): x0, y0, x1, y1 = 1, 0, 0, 1 while b != 0: q, a, b = a // b, b, a % b x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return a, x0, y0 def inverse(self, a): g, x, y = self.xgcd(a, self.mod) assert g == 1, 'modular inverse does not exist' return x % self.mod class Combination(): def __init__(self, mod=10**9 + 7): self.mod = mod self._factorial = Factorial(mod) self._modinv = Modinv(mod) def __call__(self, n, r): ''' nCr % mod ''' if not 0 <= r <= n: return 0 a, b, c = map(self._factorial, (n, r, n-r)) return a*self._modinv(b*c % self.mod) % self.mod def comb_with_repetition(self, n, r): ''' nHr % mod ''' return self.__call__(n+r-1, r) def perm(self, n, r): ''' nPr % mod ''' if not 0 <= r <= n: return 0 a, b = map(self._factorial, (n, n-r)) return a*self._modinv(b) % self.mod comb = Combination() perm = comb.perm comb_with_repetition = comb.comb_with_repetition from re import split for _ in range(int(input())): q, n, r, *_ = split('[(,)]', input()) if q == 'C': print(comb(n, r)) elif q == 'P': print(perm(n, r)) else: print(comb_with_repetition(n, r))