I think no need of DP, for all c,d<=1000 find out all values of c^3+d^4 there will be around 10^6 values, store them and sort that array (A). Now for each a,b find out all possible values of a+b^2 similarly call it array B now for each element B[i] of B do binary search on A and find count of all values such that A[i][+B[j]<=S , so add j to ans each time.