1 - If you are encoding ACM, avoid dynamic allocation of / new . It is slower and is an exception due to segfaults. Try to statically highlight everything by looking at the borders from the problem statement.
2 - The problem you want to solve is the Backpack problem. If you want, you can find many resources and solutions for it on the Internet / Wikipedia.
3 - In the deal with DP, caching is used, you only need to calculate the values ββof the recursive function once. In your case, you have 2 ^ n possible spplitings of stones, but provided that each stone has a maximum weight W, for a set of stones there is only n * W weight.
So, can we make a function F (w) that determines if there are many stones in a stone that contain up to w? If so, we can find an algorithm with only n * W iterations instead of 2 ^ n!
The answer is yes! But you probably need to place some order to make it work. Let G (w, n) be defined as follows:
G(w, n) = (true, s) if there is some set s containing only from the first n stones that adds up to w (false, _) if there is no such set.
Now we need to compute G (w, NROCKS) to find F (w)!
It is easy to find a recursive definition that computes G:
G(0, 0) = (true, {}) G(W, 0) = (false, _) G(W, N) = G(W, N-1)
Although you could just directly implement this function, it will still have exponential runtime (I won this, but think about an example of a traditional fibonacci function).
The DP trick accurately observes that there is a limited number of inputs that we will ever use for this function (from 0 to NROCKS * max (MAXWEIGHT) and N from 0 to NROCKS), so we can use NROCKS * MAXWEIGHT in the matrix NROCKS (or something similar) as a look-up table to avoid double-computing.