Editorial for Difficulties
Use this editorial only when stuck, and do not copy-paste code from it.
Please be respectful to the problem author and editorialist. Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
If every problem had a distinct label, there would be n! ordered problemsets.
Problems with the same label are indistinguishable, so this overcounts. For each label i the ai copies can be permuted freely without changing the sequence, so divide by ai!.
The number of distinct sequences is the multinomial coefficient
a1!a2!⋯ak!n!.
Two useful special cases:
- every ai=1 (so k=n): the labels are all distinct and the answer is n!;
- one ai=n and the rest 0: every problem has the same label (or unused labels contribute 0!=1) and the answer is 1.
Another checkpoint: with two labels the formula is (a1n)=n!/(a1!a2!).
Precompute factorials and inverse factorials modulo 109+7 up to n, then multiply n!⋅∏(ai!)−1. Time is O(n).
Solution (Python)
MOD = 10**9 + 7
MAXN = 10**6 + 5
fact = [1] * MAXN
for i in range(1, MAXN):
fact[i] = fact[i - 1] * i % MOD
invfact = [1] * MAXN
invfact[MAXN - 1] = pow(fact[MAXN - 1], MOD - 2, MOD)
for i in range(MAXN - 2, -1, -1):
invfact[i] = invfact[i + 1] * (i + 1) % MOD
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = fact[n]
for x in a:
ans = ans * invfact[x] % MOD
print(ans)
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.