Editorial for Stickers


Approach

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

This is stars and bars: the number of solutions is

(n+k−1k−1)\binom{n + k - 1}{k - 1}.

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

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

Solution (Python)

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

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.