Editorial for Toad


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: ji_mmyliu

Try working backwards from stone N. There are k ways to have reached stone N with a single jump (from N-1,N-2,...,N-k).

Let's define dp[i] as the minimum cost required to reach stone i from stone 1.

Therefore, dp[i] can be found as the minimum of all dp[i-d]+|a_i-a_{i-d}| for d in 1 \ldots k.

Let's break down the above formula: in order to get to stone i, we will choose a stone that is d to the left of i as the previous stone. The total cost is the cost needed to get from stone 1 to stone i-d plus the cost to jump from stone i-d to i. dp[i] is the minimum cost after considering every possible previous stone.

You may use either recursion with memoization or dynamic programming to calculate dp[N].

Time complexity: \mathcal{O}(Nk).

Sample solution written in Python

(It is recommended to implement the solution yourself before copy-pasting the official solution)

N, k = map(int, input().split())
a = list(map(int, input().split())); a.insert(0, 0) # Make the array 1-indexed
dp = [1000000000] * (N + 1) # Initialize values with a large number to label as unvisited
dp[1] = 0 # Base case: it costs 0 to get to stone 1
for i in range(1, N + 1):
    for d in range(1, k + 1):
        if i - d < 1: continue # Make sure previous stone is in range
        dp[i] = min(dp[i], dp[i - d] + abs(a[i] - a[i - d]))
print(dp[N])

Comments

There are no comments at the moment.