Original problem statement Pile it up
Summary: Two player A and B play a game consisting of 2 piles of X and Y coins. Each turn he can do one of the following:
- Remove any number of coin from a single pile (at least 1 coin)
- Remove the same amount of coin from both pile
- Pass the turn. This still count as one turn.
The game ends when no move is possible and the player who cannot make a move loses. Both players play optimally. Both players calculate the outcome of the game before the game begins. The player who loses tries to maximize the number of turns in the game and player who wins tries to minimize the turns. No player can pass more than P times. A starts the game. Output the name of the winner and the number of moves in the game separated by a single space. 0 <= X, Y, P <= 1000
I came up with an O(n^3) DP solution but surely it is not good enough for this problem considering the bounds. Let d[i, j] be the minimum number of turns to win if this is your turn to play and there are i and j coins left in pile X and Y respectively. Then we have:
d[i, j] = 0 if i = j = 0
1 if (i = 0 && j > 0) or (i > 0 && j = 0) or (i = j && i > 0)
min(min(d[i-p, j]), min(d[i, j-q), min(i-r, j-r)) if a each substate is a losing position
max of all winning position substate if no losing substate is found
Finally, d[i,j] = d[i,j] + 2*P if [i,j] is a winning state and you will not win immediately from the start.
As you can see from the formulation above, this is a O(n^3) solution. I want to improve my solution to O(n^2), how can I reformulate the problem?