E - Count Sequences 2 Editorial by en_translator
The answer is a multinomial coefficient \(\dfrac{(C_1+C_2+\ldots+C_N)!}{C_1!C_2!\dots C_N!}\). A multinomial coefficient can be represented as a product of binomial coefficients:
\[\dfrac{(C_1+C_2+\ldots+C_N)!}{C_1!C_2!\dots C_N!}=\binom{C_1}{C_1}\binom{C_1+C_2}{C_2}\dots \binom{C_1+C_2+\dots +C_N}{C_N}\]
There are several ways to compute binomial coefficients modulo \(M\) (which is not necessarily a prime). This time we have the constraint \(\sum C\leq 5000\), so the following formula on binomial coefficients allows us to precalculate \(\binom{n}{k}\ (0\leq k\leq n\leq 5000)\) easily.
\[\binom{n}{k}=\binom{n-1}{k-1}+\binom{n-1}{k}\]
Therefore, each test case can be solved in \(O(N)\) time.
T, mod = map(int, input().split())
K = 5010
binom = [[0] * K for i in range(K)]
binom[0][0] = 1
for n in range(1, K):
binom[n][0] = 1
for k in range(1, n + 1):
binom[n][k] = (binom[n - 1][k - 1] + binom[n - 1][k]) % mod
for _ in range(T):
N = int(input())
C = list(map(int, input().split()))
ans = 1
s = 0
for i in C:
s += i
ans *= binom[s][i]
ans %= mod
print(ans % mod)
posted:
last update: