Editorial for Carnival Game


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: ThingExplainer

This problem can be solved with dynamic programming. First, define b_{i, j} to represent the j^{th} board on the i^{th} layer for (1 \le i \le N - 1), or the j^{th} bucket on the i^{th} layer for i = N.

Define dp[i][j] to be minimum cost to reach b_{i, j}. Note that the ball can come from either b_{i - 1, j} or b_{i - 1, j - 1}. Define the cost c_{left} to be 0 if b_{i - 1, j - 1} is R or 1 if b_{i - 1, j - 1} is L. Similarly, define the cost c_{right} to be 0 if b_{i - 1, j} is L or 1 if b_{i - 1, j} is R. This extra cost is due to the fact that if the left/right board on the previous layer does not direct the ball to the current board, we will have to flip it so that it does.

Our general transition goes something like this:

\displaystyle dp[i][j] = \min(dp[i - 1][j - 1] + c_{left}, dp[i - 1][j] + c_{right})

Now, to find the maximum P, we can simply take \max(t_i - dp[N][i]) where (1 \le i \le N).

However, how do we know exactly what boards we flipped throughout the course of our calculation?

The answer is to store the optimal paths taken in a backtracking array. Say bt[i][j] is 0 if the ball came from b_{i - 1, j - 1}, or 1 if the ball came from b_{i - 1, j} on some optimal path to b_{i, j}. This can be calculated while we fill the dp matrix. If our maximum P happens when the ball lands in the bucket at index idx, we can start our backtracking from bt[N][idx] and move upwards to b_{i - 1, j} or b_{i - 1, j - 1} depending on the state of bt[i][j].

If at any time, we move in some direction that contradicts the movement that the ball would have had if it landed on b_{i, j} in the original input, we add b_{i, j} to the list of flipped boards, which we output after we are done backtracking.


Comments

There are no comments at the moment.