公式

E - LRUD Moving 解説 by en_translator


First, paint the grind in the checkerboard pattern: specifically, paint cell \((i,j)\) black if \(i+j\) is even, and white if odd. Then the color of the cell where the piece is located at always changes by every move.

Let us consider the necessary and sufficient condition for the answer being Yes.

[1] If \(N\) is odd

Cells \((1,1)\) and \((N,N)\) are both painted black, so the \((N^2-3)\) cells the piece visits must have colors white → black → white → … → white, but this is impossible because \(N^2-3\) is even. Thus, the answer is No.

[2] If \(N\) is even

By the same discussion as [1], the \((N^2-3)\) cells on the way must be white → black → white → … → white. If \((A+B)\) is even, there will be more black cells than white, so the answer is No.


Therefore, the answer is Yes only if

  • \(N\) is even;
  • \(A+B\) is odd.

Actually, this is a necessary and sufficient condition.

Given \(N,A\), and \(B\) satisfying these conditions, let us construct a valid LRUD string.

The original problems considers an \(N\times N\) grid, but we generalize it into an \(H\times W\) grid.

We will solve the problem recursively.

If \(A > 2\), we can begin the tour with RR...RDLL...LD so that the remaining problem is reduced to \((H,W,A,B) \leftarrow (H-2,W,A-2,B)\) case. Also, if \(H-A+1 > 2\), we can end the tour with RR...RDLL...LD to reduce it to \((H,W,A,B) \leftarrow (H-2,W,A,B)\). By repeating these reductions, we can boil down the problem to \(H=2\) case.

The same discussion applies to \(W\) axis, so that the problem is reduced to \((H,W)=(2,2)\), in which case either \((A,B)=(1,2),(2,1)\) holds, and both can be solved directly.

The problem can be solved by appropriately implementing this algorithm. The time complexity is \(O(N^2)\) per test case.

In the following code, the recursive reduction is implemented as loops, where the prefixes and suffixes are maintained individually.

Sample code (Python 3)

for _ in range(int(input())):
    n, a, b = map(int, input().split())
    a, b = a - 1, b - 1
    if n % 2 == 1 or (a + b) % 2 == 0:
        print("No")
        continue
    s1 = []
    s2 = []
    for _ in range(n // 2 - 1):
        s = "R" * (n - 1) + "D" + "L" * (n - 1) + "D"
        if a >= 2:
            s1.append(s)
            a -= 2
        else:
            s2.append(s[::-1])
    for _ in range(n // 2 - 1):
        s = "DRUR"
        if b >= 2:
            s1.append(s)
            b -= 2
        else:
            s2.append(s[::-1])
    assert (a, b) in ((0, 1), (1, 0))
    if (a, b) == (0, 1):
        s1.append("DR")
    else:
        s1.append("RD")
    ans = "".join(s1) + "".join(s2[::-1])
    print("Yes")
    print(ans)

投稿日時:
最終更新: