Editorial for Difficulties


Approach

If every problem had a distinct label, there would be n!n! ordered problemsets.

Problems with the same label are indistinguishable, so this overcounts. For each label ii the aia_i copies can be permuted freely without changing the sequence, so divide by ai!a_i!.

The number of distinct sequences is the multinomial coefficient

n!a1! a2! ⋯ ak!\dfrac{n!}{a_1! \, a_2! \, \cdots \, a_k!}.

Two useful special cases:

  • every ai=1a_i = 1 (so k=nk = n): the labels are all distinct and the answer is n!n!;
  • one ai=na_i = n and the rest 00: every problem has the same label (or unused labels contribute 0!=10! = 1) and the answer is 11.

Another checkpoint: with two labels the formula is (na1)=n!/(a1! a2!)\binom{n}{a_1} = n! / (a_1! \, a_2!).

Precompute factorials and inverse factorials modulo 109+710^9 + 7 up to nn, then multiply n!⋅∏(ai!)−1n! \cdot \prod (a_i!)^{-1}. Time is O(n)O(n).

Solution (Python)

Code 1
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.