As a follow-up to this question , I've found a recursive algorithm that solves the given problem, but it runs too slow to pass all given tests.
int solve(int i, int crane1_pos, int crane2_pos, int dist)
{
if(i == n)
{
return dist;
}
int dist1 = dist + get_dist(crane1_pos, t[i].first);
int dist2 = dist + get_dist(crane2_pos, t[i].first);
return min(solve(i + 1, t[i].second, crane2_pos, dist1), solve(i + 1, crane1_pos, t[i].second, dist2));
}
Where, get_dist is a function that looks like this:
int get_dist(int crn_pos, int fin_pos)
{
if(crn_pos == -1)
return 0;
return abs(crn_pos - fin_pos);
}
$t$ in this particular situation is a vector of pair<int, int>
, $n$ is the size of this vector and the initial call of the function is solve(0, -1, -1, 0)
.
I'm pretty sure this could be further improved by using DP, but upon doing some research on this issue, I found that I'm unable to transform this recurrence into some form of dynamic programming. I've derived the recurrence trees for several examples and I can't find the overlapping subproblems and a way to use memoization.
So I guess my question is, how do you turn this recurrence into DP?