Editorial for Ground Is Lava


Walking directly from aa to bb is always possible, so one candidate answer is:

∣a−b∣.|a-b|.

The only other useful idea is to use the pole-vault move, which connects consecutive multiples of kk. If a route uses these vaults, then it has the following form:

  1. walk from aa to some multiple kxkx,
  2. use vault moves between multiples of kk,
  3. walk from some multiple kyky to bb.

For fixed integers xx and yy, the cost of this route is:

∣a−kx∣+∣x−y∣+∣b−ky∣.|a-kx| + |x-y| + |b-ky|.

Now we only need to know which multiples are worth trying. For the start point aa, it is enough to consider the closest multiple of kk on the left and the closest multiple of kk on the right. These correspond to:

⌊ak⌋and⌊ak⌋+1.\left\lfloor \frac{a}{k} \right\rfloor \quad\text{and}\quad \left\lfloor \frac{a}{k} \right\rfloor + 1.

The same is true for bb.

Why is this enough? Suppose we choose a multiple farther away from aa than both of these. Moving it one step closer to aa changes the vaulting part by at most 11, but decreases the walking distance from aa by kk. Since k≥1k \geq 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∈{⌊ak⌋,⌊ak⌋+1},y∈{⌊bk⌋,⌊bk⌋+1}.x \in \left\{\left\lfloor \frac{a}{k} \right\rfloor,\left\lfloor \frac{a}{k} \right\rfloor+1\right\}, \qquad y \in \left\{\left\lfloor \frac{b}{k} \right\rfloor,\left\lfloor \frac{b}{k} \right\rfloor+1\right\}.

The answer is the minimum of the direct walking cost and these four values.

Be careful with negative values of aa and bb. In C++, integer division rounds toward zero, not toward −∞-\infty, so a custom floor-division function is needed.

Complexity

Only a constant number of candidates are checked, so the time complexity is:

O(1).O(1).

The memory complexity is also:

O(1).O(1).

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.