Algorithm
A route exists if and only if is even and
If this condition does not hold, print No. Otherwise, print Yes and make the following moves:
U, reaching .A feasible case requires printing characters and takes time. An infeasible case takes time. The total time complexity is .
Proof
An odd grid size is impossible.
Color each grid point according to the parity of . Every move changes the color, so any route returning to its starting point has even length. A cycle visiting every point exactly once has length . Therefore, must be even.
Every valid cycle has the same area.
Two horizontal or vertical unit grid segments can intersect or overlap only by sharing a grid point. No point is revisited except for the final return to the starting point. Thus, a valid cycle forms a simple polygon.
The polygon lies inside the square . Every integer grid point strictly inside it must therefore belong to . However, the cycle visits every point in , placing all of them on its boundary. Consequently, the number of interior grid points is .
Subtask 1
For , exhaustively enumerate all routes while recording the visited points. Whenever a route visits every point and can return to the start in one more move, compute its area with the shoelace formula. Store a route for each area found, then look up the requested .
After the first move, the immediately preceding point cannot be visited again, so each extension considers at most directions. The search for one size takes time. The only possible sizes are , so perform the search once per size and reuse the results.
RDUD, followed by moves L.The boundary consists of unit grid segments and contains exactly distinct grid points. By Pick's theorem, its area is
Hence, the requested area must equal this value.
The construction visits every point when is even.
The first stage visits the entire column . The middle stage visits all points with in each column from through , alternating between downward and upward traversal. These points are distinct and do not overlap with the first stage.
Since is even, the last column is traversed downward, ending at . The final stage visits the remaining points in the row and returns to the start. Thus, every grid point is visited exactly once, apart from the final return to the starting point.
The total number of moves is
Its area equals the value proved above, so the stated condition is also sufficient.
Solution written by GPT6