Editorial
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:
- Make moves
U, reaching . - For , first make one move . If is even, make moves ; otherwise, make moves .
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.