Every L takes both cells of one column and one cell of an adjacent column. It therefore creates an empty column, separating the remaining cells on its two sides into independent games.
In each interval between empty columns, only the end columns may have a single cell; every interior column still has two cells. Every move preserves this property.
Let be the number of remaining cells in an interval. Every move leaves two intervals of sizes and . Conversely, every is achievable: list the cells column by column from left to right. Any three consecutive cells contain both cells of one column and a cell of a neighboring column, so taking the three cells immediately after the first cells realizes that split. Other orientations produce no additional size pairs.
Thus the Grundy number depends only on the number of cells. Write it as . Then
and for ,
Here is the smallest nonnegative integer absent from a set, and is bitwise XOR.
Initially there is one interval with cells. Print YES if , and NO otherwise.
Let be the largest input value of . Precomputing through takes time and space; each test case then takes time. Total time is and space including stored input is .
For subtask 1, . Use a bitmask of the cells and memoized search over every legal L. Cache the answer for each distinct . With , the bounds are time and at most space. Subtask 2 uses the Grundy recurrence above.
Solution written by GPT