G - Constrained Nim 2 Editorial by spheniscine


The following assumes familiarity with the Sprague-Grundy theorem and its application.

Let \(g_x\) represent the Grundy number of a pile of \(x\) stones. One can think of calculating it naively using DP as \(g_x = \text{mex}_{x-R \le i \le x-L}\ g_{i}\), but the numbers involved may be too large to do so.

However, you could work a few smaller examples by hand and/or code and notice a pattern, and conjecture that:

\[g_x = \left\lfloor\frac{x \text{ mod } (L+R)}{L}\right\rfloor\]

We shall prove this conjecture for ourselves.

For \(x < L+R\), note that for piles of size \(iL \le x < (i+1)L\), the “window” of \(g_i\) for \(x-R \le i \le x-L\) will include all non-negative integers less than \(i\), therefore \(g_x = i = \lfloor x / L \rfloor\).

For \(L+R \le x < 2(L+R)\), for piles of size \(L+R+iL \le x < L+R+(i+1)L\), we note the “window” includes all non-negative integers less than \(i\), but misses the segment of \(g\) that was equal to \(i\), therefore the mex is once again \(i\). And we can see the pattern repeats for \(x \ge 2(L+R)\).

The Sprague-Grundy theorem says that the Grundy value for the disjunctive sum of several impartial games is equal to the xor-sum of the Grundy values of the component games, and that the game is a first-player win iff the Grundy value is not \(0\). We can thus discover the Grundy value of the combined game, and thus the winning player, in \(O(N)\).

posted:
last update: