---
id: 892
lang: en
translation_of: index.md
source_sha256: 06fcc70acff5ff23ebb7d75fba2c8943daa661e6707d520f2f36daeaed11f716
title: "Educational DP Contest: M – Candies — Solution"
description: "The transition is a range sum over the previous row, so precomputing prefix sums makes each transition an O(1) lookup."
tags: ["OI","DP","Prefix Sums","Counting","Counting DP","Prefix Sum Optimization"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "预处理出前缀和dp[i-1][k-1] kept literal as “precompute the prefix sums dp[i-1][k-1]”; 大的减小的 rendered as “subtracting the smaller one from the bigger one”."
---

## Main Idea

<span class="slang" data-zh="傻逼" data-gloss="shǎbī. A vulgar insult, roughly “idiot” or “stupid”.">Stupid</span> me even went and did a multiset inclusion–exclusion, just to make myself miserable.

First, analyze the problem statement; it’s not hard to come up with the transition equation:

$$
dp[i][j] = dp[i-1][j]+\sum_{k = limit[i]}^{j} dp[i-1][k]
$$

Then consider spending $O(n)$ time to first precompute the prefix sums $dp[i-1][k-1]$, and then just query in $O(1)$ by subtracting the smaller one from the bigger one.

## Code

```cpp
// M.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 110, MAX_K = 1e5 + 200, MOD = 1e9 + 7;
ll n, limit[MAX_N], dp[MAX_N][MAX_K], k, mxk, prefix[MAX_K];
int main()
{
    scanf("%lld%lld", &n, &k);
    for (int i = 1; i <= n; i++)
        scanf("%lld", &limit[i]), dp[i][0] = 1;
    dp[0][0] = 1;
    for (int i = 1; i <= n; i++)
    {
        prefix[i] = 0;
        for (int j = 1; j <= k + 1; j++)
            prefix[j] = prefix[j - 1] + dp[i - 1][j - 1];
        for (int j = 1; j <= k; j++)
        {
            dp[i][j] = dp[i - 1][j] + prefix[j] - prefix[max(0LL, j - limit[i])];
            dp[i][j] %= MOD;
        }
    }
    printf("%d", dp[n][k]);
    return 0;
}
```
