Editorial for Ground Is Lava
Walking directly from a to b is always possible, so one candidate answer is:
∣a−b∣.The only other useful idea is to use the pole-vault move, which connects consecutive multiples of k. If a route uses these vaults, then it has the following form:
- walk from a to some multiple kx,
- use vault moves between multiples of k,
- walk from some multiple ky to b.
For fixed integers x and y, the cost of this route is:
∣a−kx∣+∣x−y∣+∣b−ky∣.Now we only need to know which multiples are worth trying. For the start point a, it is enough to consider the closest multiple of k on the left and the closest multiple of k on the right. These correspond to:
⌊ka⌋and⌊ka⌋+1.The same is true for b.
Why is this enough? Suppose we choose a multiple farther away from a than both of these. Moving it one step closer to a changes the vaulting part by at most 1, but decreases the walking distance from a by k. Since k≥1, this never makes the answer worse. So an optimal route that uses the pole can always be found using one of the two neighboring multiples near each endpoint.
Therefore, we try at most four vault candidates:
x∈{⌊ka⌋,⌊ka⌋+1},y∈{⌊kb⌋,⌊kb⌋+1}.The answer is the minimum of the direct walking cost and these four values.
Be careful with negative values of a and b. In C++, integer division rounds toward zero, not toward −∞, so a custom floor-division function is needed.
Complexity
Only a constant number of candidates are checked, so the time complexity is:
O(1).The memory complexity is also:
O(1).
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.