I'm trying to come up with a DP solution to Moons and Umbrellas from Code Jam's Qualification Round 2021. Below is my working recursive solution, based on their analysis:
import sys
from functools import lru_cache
sys.setrecursionlimit(5000)
T = int(input())
for case in range(1, T+1):
X, Y, S = input().split()
X = int(X)
Y = int(Y)
S = tuple(S)
@lru_cache(maxsize=128)
def cost(S):
if len(S) <= 1:
return 0
if S[0] == '?':
return min(cost(('C',) + S[1:]), cost(('J',) + S[1:]))
if S[0] != '?' and S[1] == '?':
return min(cost((S[0],) + ('C',) + S[2:]), cost((S[0],) + ('J',) + S[2:]))
if S[0] == S[1]:
return cost(S[1:])
if S[0] == 'C' and S[1] == 'J':
return X + cost(S[1:])
if S[0] == 'J' and S[1] == 'C':
return Y + cost(S[1:])
print(f'Case #{case}: {cost(S)}')
The problem in a nutshell is given a string of C's, J's, and ?s (e.g. CCJCJ??JC or JCCC??CJ), the question marks should be replaced by either C or J. Minimize the cost of transitioning from Cto J or vice versa. The two types of transitions have different costs.
How do I convert it to a DP solution using the bottom-up approach?
This solution works for all 3 Test sets: