Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

Let dp[a]\texttt{dp[a]} be the number of ways to achieve the sum aa using the current set of balls. We'll update our array dynamically as balls are added or removed.

If we add a ball with value xx, we loop over all jj from KK to xx while performing the following transition:

dp[j]:=dp[j]+dp[j-x]\texttt{dp}[j] := \texttt{dp[j]}+\texttt{dp[j-x]}

An important thing to note is that we have to iterate backward; otherwise we might add this one ball multiple times.

To remove a ball of value xx, we do the same thing, but in reverse. This entails going from xx to KK and decrementing instead of incrementing.

Implementation

Time Complexity: O(QK)\mathcal{O}(QK)

C++

#include <iostream>
#include <vector>
const int MOD = 998244353;
int main() {
int q, k;
std::cin >> q >> k;
std::vector<long long> dp(k + 1);

Java

import java.io.*;
import java.util.*;
public class Main {
private final static int MOD = 998244353;
public static void main(String[] args) {
Kattio io = new Kattio();
int q = io.nextInt();
int k = io.nextInt();

Python

MOD = 998244353
q, k = map(int, input().split())
dp = [0] * (k + 1)
dp[0] = 1
for i in range(q):
a = input().strip()
t, x = a.split()

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!