---
id: 1896
lang: en
translation_of: index.md
source_sha256: c2fd5fdbea3e8c0782632a513b986fc67f5167a9efa29798fecc0db27147ea2c
title: "AtCoder Grand Contest 002E - Leftmost Ball — Solution"
description: "We only need the number of 0s to never fall below the number of colors, so we place all the balls at once and run a DP on the count of 0s and colors."
tags: ["OI","DP","Counting"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "同质问题 rendered as “the issue of identical balls” (balls of the same color are indistinguishable)."
---

## Main Idea

We notice that we only need to make sure that at any moment the number of $0$s is greater than or equal to the number of colors. Directly considering stuffing the balls in one by one means dealing not only with the issue of identical balls but also with the concrete arrangement of colors, which is a real pain, so instead let's place all the balls on the sequence in one go: let $dp[i][j]$ be the state with $i$ $0$s and $j$ colors, and we can transition like this:

$$
dp[i][j] = dp[i - 1][j] + {n - i + (n - j + 1) \times (k - 2) - 1 \choose k - 2 } dp[i][j - 1] (n - j + 1)
$$

To explain: we fix the position of this color's ball at the leftmost point where it can be placed, then multiply by $n - j + 1$ to do the coloring, and choose positions for the remaining $k-2$ balls.

<!--more-->

## Code

```cpp
// AGC002F.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 2020, mod = 1e9 + 7;

int n, k, dp[MAX_N][MAX_N], fac[MAX_N * MAX_N], fac_inv[MAX_N * MAX_N], fac_tot;

int quick_pow(int bas, int tim)
{
    int ret = 1;
    while (tim)
    {
        if (tim & 1)
            ret = 1LL * ret * bas % mod;
        bas = 1LL * bas * bas % mod;
        tim >>= 1;
    }
    return ret;
}

int comb(int upper, int lower) { return 1LL * fac[upper] * fac_inv[lower] % mod * fac_inv[upper - lower] % mod; }

int main()
{
    scanf("%d%d", &n, &k), fac_tot = n * k;
    if (k == 1)
        puts("1"), exit(0);
    for (int i = fac[0] = 1; i <= fac_tot; i++)
        fac[i] = 1LL * fac[i - 1] * i % mod;
    fac_inv[fac_tot] = quick_pow(fac[fac_tot], mod - 2);
    for (int i = fac_tot - 1; i >= 0; i--)
        fac_inv[i] = 1LL * fac_inv[i + 1] * (i + 1) % mod;
    dp[0][0] = 1;
    for (int i = 1; i <= n; i++)
        for (int j = 0; j <= i; j++)
        {
            dp[i][j] = dp[i - 1][j];
            if (j > 0)
                dp[i][j] = (1LL * dp[i][j] + 1LL * comb(n - i + (n - j + 1) * (k - 1) - 1, k - 2) * dp[i][j - 1] % mod * (n - j + 1) % mod) % mod;
        }
    printf("%d\n", dp[n][n]);
    return 0;
}
```
