B - Japanese "Knight's Tour" 解説 by evima
First, if \(H\) is even, the answer is \(0\) (because the knight cannot be placed on odd-numbered rows). Hereafter, we consider the case where \(H\) is odd.
We solve by case analysis for when \(W\) is odd and when \(W\) is even, but since the discussion is almost the same for both cases, we will only explain the odd case.
First, since the knight’s movement is a bit difficult to think about, we will explain by appropriately rearranging the rows and replacing them with diagonal downward movements.
This problem can be considered as counting the number of ways such that when we draw directed edges from every square to one of the two diagonally downward squares, the entire structure forms a single cycle.
For example, suppose we draw an edge from \((0,0)\) to \((1,1)\). Then, an edge cannot be drawn from \((2,0)\) to \((1,1)\), so the edge starting from \((2,0)\) will go to \((3,1)\). Repeating this, since \(W\) is odd, the destinations of edges are determined for all \((0,\ast)\). Particularly, for all \((0,\ast)\), whether to draw an edge to the bottom-left or bottom-right will be consistent.
Therefore, if we fix the first \(H\) moves, that is, as a problem of drawing edges, if we fix the method of moving \(H\) times following edges starting from \((0,0)\), all edges will be determined similarly.
After that, it suffices for this to form a single cycle. This can be verified to be necessary and sufficient that \(\gcd(W,i)=1\) when the position after \(H\) moves is \((i,0)\). (Necessity is obvious, and sufficiency can be proved from the fact that when \(i\) is fixed, whether to draw an edge to the bottom-left or bottom-right is consistent for all \((i,\ast)\).) Now, we have found the desired condition, and the answer can be easily calculated using binomial coefficients.
The case where \(W\) is even can also be solved with almost the same consideration. Simply put, we can perform the same discussion by replacing “the first \(H\) moves” with “the first \(2H\) moves”.
From the above, this problem can be solved in \(\mathrm{O}(H \log W)\) time or similar, which is sufficiently fast.
投稿日時:
最終更新: