Editorial for Stickers


Remember to use this editorial only when stuck, and not to 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

The stickers are identical and the people are distinct, so a distribution is a tuple of non-negative integers (x_1, \ldots, x_k) with x_1 + \cdots + x_k = n.

This is stars and bars: the number of solutions is

\binom{n + k - 1}{k - 1}.

When n = 0 this is \binom{k - 1}{k - 1} = 1 (everyone gets nothing). When k = 1 this is \binom{n}{0} = 1 (the only person gets every sticker).

Precompute factorials and inverse factorials modulo 10^9 + 7 up to n + k - 1 \le 2 \cdot 10^6. Then \binom{n + k - 1}{k - 1} = (n + k - 1)! \cdot (k - 1)!^{-1} \cdot n!^{-1}. Time is O(n + k) for the precomputation.

Solution (Python)

MOD = 10**9 + 7
MAXN = 2 * 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


def nCr(n, k):
    if k < 0 or k > n:
        return 0
    return fact[n] * invfact[k] % MOD * invfact[n - k] % MOD


n, k = map(int, input().split())
print(nCr(n + k - 1, k - 1))

Comments

There are no comments at the moment.