Official

C - Robot on Grid Editorial by evima


The sum of the numbers of paths the robot can take from \((1, 1)\) to \((H, W)\) over all ways to write letters, is equal to the following: the sum, for all paths from \((1, 1)\) to \((H, W)\), of the numbers of ways to write letters so that the robot can take the paths.

Instead of dealing with the former, let us try to find the latter. We assume that, from an empty square, both moves are available: right and down.

Let \(\mathrm{dp}(h,w,k)\) be the number of paths the robot can take from \((1,1)\) to \((h,w)\) that traverse \(k\) empty squares. On the empty squares traversed by the robot, we need to write X or the letter corresponding to the direction the robot went from that square. On the other squares, we are allowed to write any letter. Thus, the answer is \(\sum_{1 \leq k \leq H+W} \mathrm{dp}(H,W,k) 2^{k}3^{HW-K-k}\), which we can find in \(O(HW(H+W))\) time.

Here, instead of keeping \(k\) as a part of the state, we can multiply the numbers by \(\frac{2}{3}\) in the transition and by \(3^{HW-K}\) in the end, we can find it in \(O(HW)\) time, which is fast enough for \(H,W \leq 5000\).

posted:
last update: