Explanation
Let be the number of ways to achieve the sum 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 , we loop over all from to while performing the following transition:
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 , we do the same thing, but in reverse. This entails going from to and decrementing instead of incrementing.
Implementation
Time Complexity:
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 = 998244353q, k = map(int, input().split())dp = [0] * (k + 1)dp[0] = 1for 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!