I am currently working on this problem:
A certain string-processing language offers a primitive operation which splits a string into two pieces. Since this operation involves copying the original string, it takes n units of time for a string of length n, regardless of the location of the cut. Suppose, now, that you want to break a string into many pieces. The order in which the breaks are made can affect the total running time. For example, if you want to cut a 20-character string at positions 3 and 10, then making the first cut at position 3 incurs a total cost of 20+17=37, while doing position 10 first has a better cost of 20+10=30. Give a dynamic programming algorithm that, given the locations of m cuts in a string of length n, finds the minimum cost of breaking the string into m + 1 pieces.
I managed to represent the problem as a recurrence and came up with the following recursive solution to the problem.
def recursive(M, N):
if len(M) == 0:
return 0
else:
c_min = float('inf')
for c in M:
lt_cuts = [d for d in M if d < c]
gt_cuts = [e - c for e in M if e > c]
c_min = min(c_min, N + recursive(lt_cuts, c) + recursive(gt_cuts, N - c))
return c_min
Normally once I find the recursive form of a problem, adapting it to a dynamic algorithm is pretty easy. This time I've been banging my head against this problem for an entire day and I can't find a single working solution. Can anyone give me some hints or useful snippets? Anything would be appreciated.