## F - I hate Shortest Path Problem Editorial by evima

When \(k\) is fixed, every path has the same number \(k\) of moving downwards, so we want to find the number of minimum times to move to the right.

The optimal strategy of moving is to move downwards as much as possible, and if not possible, move to the right. This is due to that fact that, since we want to minimize the number of movement towards right, we can always move to the right in the same way in every row, thus we do not have to move to the right until needed. Now, the path is uniquely determined when the starting square is fixed.

Calculate in the increasing order of \(k\) while managing the possible \(W\) pairs of positions of stariting end ending squares counted from the leftmost one. In the \(k\)-th process, for each pair such that its ending square is between \(A_k\) and \(B_k\), inclusive, upadte its ending square to \(B_k+1\), then answer the minimum difference of starting and ending squares. Note that however, when \(B_k = W\), the endpoint should be updated to \(\infty\) instead of \(W+1\).

This operations can be processed with semgnet trees, but this can also be processed with ordered sets.

Once the ending square of two pairs becomes the same, they will have the common endpoint from then on, so all of them except for the one having the maximum starting point can be ignored. Prepare a set of (ending point, staring point) and a multiset of endting points subtracted by starting points, and update them while removing the elements that are no longer needed. The total time complexity will be \(O((H+W)log(H+W))\).

posted:

last update: