If you haven't tried the NPCAPC contest before and you want to do some kind of virtual participation, this editorial is not for you. I do not intend to spoil the questions and the contest experience.
For each layer of DP, you can calculate the values that contribute to the answer with the respective k. First, consider only transferring those that only add A[i] to transfer (those that use A[i]), and also make sure that you perform min(M, sum) to make sure there is no overflow. Then the answer for each k is dp[i][M] * C(N — i, k). This is because we can choose an index afterwards and it does not change the outcome. Remember to add the dp values from the previous layer too after the calculations.
In this case, we know the specific states that we want to go to (using the encoding 7 * i + j). Then we want to deduct it from the number of alphabets that we can use and does not affect our answer (52 initially).
In my code, I precomputed the matrices and stored them inside an array so that I didn't have to waste extra time.
After finding the sum, let S = sum / 2. Then we can utilize a dp with the states defined as dp[i][j][k] = number of ways that we can have after considering i numbers in the list, gotten j indices, and sum = k. dp[i][j][k] = dp[i — 1][j][k] + dp[i — 1][j — 1][k — A[i]]. When we don't perform anything we automatically transfer the dp[i — 1][j][k] from the previous layer. If we take A[i], that means that we must come from the previous layer, taken j — 1, and previous sum = k — A[i]. Make sure no out-of-bounds is performed in the code.
Then the answer is simply the sum of dp[N][i][S] * (i!) * (N — i)!