B - Frog 2 Editorial
by
iastm
Let \(f(i)\) be the minimum cost of reaching Stone \(i\). Since the frog is initially on Stone \(1\), \(f(1)=0\).
For \(i\geq2\), the frog can reach Stone \(i\) from Stone \(j\) if \(i-K\leq j\leq i-1\). Since there are no stones before Stone \(1\), it is also required that \(j\geq1\). Therefore,
\[f(i)=\min_{\max(i-K,1)\leq j\leq i-1}\{f(j)+|h_j-h_i|\}.\]
We can implement the above logic using a nested loop to iterate over all possible values of \(i\) and \(j\) to compute \(f(N)\), the minimum cost of reaching Stone \(N\). Since we iterate over \(N\) possible values of \(i\), and each loop iterates over at most \(K\) possible values of \(j\), the time complexity is \(O(NK)\).
Sample code (Python):
N, K = (int(x) for x in input().split())
H = [int(x) for x in input().split()]
dp = [0] * N
for i in range(1, N):
dp[i] = min(
dp[j] + abs(H[j] - H[i])
for j in range(max(i - K, 0), i)
)
print(dp[-1])
posted:
last update:
