Impartial Combinatorial Games

Prior knowledge: Introduction to Game Theory

This article discusses impartial combinatorial games.

Among impartial combinatorial games, normal-play Nim is the most basic and important one. The Sprague–Grundy theorem states that every impartial combinatorial game under normal play is equivalent to a single-pile Nim game. This leads to the concepts of the Sprague–Grundy function and nimbers, which completely characterize a normal-play impartial combinatorial game. Accordingly, this article first establishes the results for normal-play Nim and Sprague–Grundy theory. It then discusses several impartial combinatorial games commonly encountered in algorithmic competitions.

Finally, this article briefly discusses misère Nim. Misère games are considerably more complicated than normal-play games and rarely appear in algorithmic competitions. Unless stated otherwise, every game mentioned in this article is assumed to be a normal-play impartial combinatorial game.

“States”, “Positions”, and “Games”

This article uses these three terms interchangeably. In game theory, the state of a game usually includes all information that may be relevant to the game up to a given point in time. In general, a game state may include the players’ previous actions, the values of random variables that have been realized, and the information known to both players. A game position is not a standard term in game theory in the same sense; it usually refers to the situation faced by the players at a given moment, such as the positions of pieces on a chessboard. For impartial combinatorial games (or, more generally, zero-sum, deterministic, perfect-information games), there is no randomness, and the players’ future action sets and payoff functions do not depend on the historical path by which the current position was reached. Thus, state and position are indistinguishable, and both can be regarded as a node in the game graph. Since a game can always be described by its initial position, “position” is sometimes used to refer to the game itself.

Nim Game

The rules of Nim are simple:

Nim Game

There are nn piles of stones. The ii-th pile contains aia_i stones. Two players take turns removing any positive number of stones from any one pile. The player who removes the last stone wins.

It is easy to verify that Nim is a normal-play impartial combinatorial game.

Example

For example, suppose there are 33 piles containing 2,5,42,5,4 stones, respectively. One may remove stones from pile 11, taking 22 stones and giving the position 0,5,40, 5, 4; one may also remove stones from pile 22, taking 44 stones and giving 2,1,42, 1, 4. If at some point the position becomes 0,0,50, 0, 5, player A may remove the stones from pile 33, taking 55 stones, that is, the last remaining stone, and thereby win.

Game Graphs and States

The possible changes of position in Nim can be described by a game graph.

Treat every possible state as a node and draw an edge from each state to every successor state (that is, every state reachable by one operation). The resulting graph is a directed acyclic graph, called the game graph. It is acyclic because every operation in Nim strictly decreases the total number of stones.

Example

For example, the game graph of a Nim game whose initial position has 33 piles containing 1,1,21,1,2 stones can be drawn as follows:

Example of a game graph
Example of a game graph

As will be shown shortly, the red nodes in the graph are winning positions, while the black nodes are losing positions.

Because Nim is an impartial combinatorial game, whether a player has a winning strategy depends only on the current state, not on the player’s identity. Thus, every state can be classified as a (first-player) winning state or a (first-player) losing state, denoted by N\mathcal N and P\mathcal P, respectively1. This definition applies to all impartial combinatorial games.

The following lemma lets us classify all states inductively as winning or losing:

Lemma

In a normal-play impartial combinatorial game:

  1. A state with no successor is a losing state P\mathcal P;
  2. A state is a winning state N\mathcal N if and only if at least one of its successors is a losing state P\mathcal P;
  3. A state is a losing state P\mathcal P if and only if all of its successors are winning states N\mathcal N.
Proof

For the first statement, if the player has no legal action, that player has already lost the game.

For the second statement, if a state has at least one losing successor, the player can move to that losing state. The opponent then faces a first-player-losing state, so the player eventually wins.

For the third statement, if no successor is losing, every move reaches a winning state. The opponent then faces a first-player-winning state, so the player eventually loses.

The game graph of every impartial combinatorial game is a directed acyclic graph. Therefore, after drawing the game graph, these three properties allow us to compute whether every state is winning or losing in O(∣V∣+∣E∣)O(|V|+|E|) time, where ∣V∣|V| is the number of states in the graph and ∣E∣|E| is the number of edges, namely the total number of available actions over all states.

This lemma can be extended to misère games and to the case where the directed graph may contain cycles. See the section Directed Graph Games for the relevant discussion.

Nim Sum

Let us continue examining Nim.

By drawing the game graph, one can determine whether a position is winning for the first player in Ω(∏i=1nai)\Omega(\prod_{i=1}^na_i) time. However, this complexity is too high for practical use. In fact, whether a Nim position is winning for the first player depends only on the Nim sum of the pile sizes.

Nim Sum

The Nim sum of natural numbers a1,a2,⋯ ,ana_1,a_2,\cdots,a_n is defined as a1⊕a2⊕⋯⊕ana_1\oplus a_2\oplus\cdots\oplus a_n.

The Nim sum is simply the bitwise XOR operation.

Theorem

In Nim, the state (a1,a2,⋯ ,an)(a_1,a_2,\cdots,a_n) is a losing state P\mathcal P if and only if the Nim sum

a1⊕a2⊕⋯⊕an=0.a_1\oplus a_2\oplus\cdots\oplus a_n = 0.
Proof

Apply induction to all possible states:

  1. If ai=0a_i=0 for every i=1,⋯ ,ni=1,\cdots,n, the state has no successor and its Nim sum is 00, so the statement holds.

  2. Suppose k=a1⊕a2⊕⋯⊕an≠0k = a_1\oplus a_2\oplus\cdots\oplus a_n\neq 0. We must prove that the state is winning. In other words, we must construct a legal move whose successor is losing. By the induction hypothesis, it suffices to show that the successor satisfies a1′⊕a2′⊕⋯⊕an′=0a'_1\oplus a'_2\oplus\cdots\oplus a'_n=0. By the properties of the Nim sum (that is, XOR), this is equivalent to finding a pile of size aia_i from which some stones can be removed so that its new size is ai⊕ka_i\oplus k, or equivalently, ai>ai⊕ka_i>a_i\oplus k.

    Let the highest bit of kk whose value is 11 be bit dd. Then there must be some aia_i whose bit dd is 11. For the corresponding pile, we have ai>ai⊕ka_i>a_i\oplus k, because in ai⊕ka_i\oplus k, bit dd is 00, while all higher bits are the same as in aia_i.

  3. Suppose a1⊕a2⊕⋯⊕an=0a_1\oplus a_2\oplus\cdots\oplus a_n= 0. We must prove that the state is losing. By the induction hypothesis, it is enough to prove that the Nim sum of every successor is not 00. This is immediate: every legal move changes aia_i to ai′≠aia'_i\neq a_i, so the Nim sum becomes ai′⊕ai≠0a'_i\oplus a_i\neq 0.

Thus, the winning status of a Nim position can be determined in O(n)O(n) time.

Sprague–Grundy Theory

Sprague–Grundy theory states that every impartial combinatorial game is equivalent to a single-pile Nim game. This result is mainly useful when a game consists of several independent subgames. In that case, the game state can be determined by taking the Nim sum of the SG values of the subgames. If the game does not have this structure, determining whether a state is winning or losing only requires applying the lemma from the game-graph section above.

Game Notation

As explained above, every impartial combinatorial game can be described by drawing its game graph. Since the property of each state in a game graph is determined solely by its successors, a state SS in the graph can be represented by the set of its successor states.

Example (continued)

Using the game graph above as an example, we obtain the following state representations:

S0,0,0={},S0,1,0={S0,0,0}={{}},S0,0,1={S0,0,0}={{}},S0,0,2={S0,0,0,S0,0,1}={{},{{}}},S0,1,1={S0,0,0,S0,1,0,S0,0,1}={{},{{}}},S0,1,2={S0,0,2,S0,1,0,S0,1,1}={{{}},{{},{{}}}}.\begin{aligned} S_{0,0,0} &= \{\},\\ S_{0,1,0} &= \{S_{0,0,0}\} = \{\{\}\},\\ S_{0,0,1} &= \{S_{0,0,0}\} = \{\{\}\},\\ S_{0,0,2} &= \{S_{0,0,0},S_{0,0,1}\} = \{\{\},\{\{\}\}\},\\ S_{0,1,1} &= \{S_{0,0,0},S_{0,1,0},S_{0,0,1}\} = \{\{\},\{\{\}\}\},\\ S_{0,1,2} &= \{S_{0,0,2},S_{0,1,0},S_{0,1,1}\} = \{\{\{\}\},\{\{\},\{\{\}\}\}\}. \end{aligned}

Here, S0,1,0=S0,0,1S_{0,1,0}=S_{0,0,1} and S0,0,2=S0,1,1S_{0,0,2}=S_{0,1,1}.

A game can be represented by its initial state.

Although the representation of an impartial game may be complicated, a single-pile Nim game is much simpler. When there is one pile containing nn stones, it can be represented as

∗0={}, ∗n={∗m:m<n, m∈N}={∗0,∗1,⋯ ,∗(n−1)}.*0 = \{\},~*n = \{*m : m<n,~m\in\mathbf N\} = \{*0,*1,\cdots,*(n-1)\}.

Here, the notation ∗n*n denotes the single-pile Nim game (or its initial state) with nn stones.

Example (continued)

With this notation, the states in the example above can be represented simply as

S0,0,0=∗0, S0,1,0=S0,0,1=∗1, S0,0,2=S0,1,1=∗2, S0,1,2={∗1,∗2}.S_{0,0,0} = *0,~ S_{0,1,0} = S_{0,0,1} = *1,~ S_{0,0,2} = S_{0,1,1} = *2,~ S_{0,1,2} = \{*1, *2\}.

In the discussion that follows, the notation T∈ST\in S should be understood to mean that state TT is a successor of state SS.

Game Sums and Equivalence

The equivalence relation on games depends on the concept of the sum of games2.

Game Sum

For games GG and HH, their sum (or combined game) is denoted by G+HG+H and is the game

G+H={g+H:g∈G}∪{G+h:h∈H}.G + H = \{g + H : g \in G\} \cup \{G + h : h \in H\}.

A game sum can be understood as a game consisting of two subgames that proceed simultaneously without interfering with each other. At every turn, a player must choose exactly one subgame and make one move in it; the combined game ends when neither subgame has a legal move. The concept of a sum extends to any number of games and satisfies associativity and commutativity: the result of combining several games does not depend on the order in which they are combined or on the order of the games. Nim is the sum of several single-pile Nim games.

One observation is that, although every nonempty single-pile Nim game is winning for the first player, different single-pile Nim games produce different results when combined with other single-pile Nim games. For example, ∗n*n produces a losing game only when combined with another ∗n*n; combined with any other game ∗n′≠∗n*n'\neq *n, it produces a winning game.

This observation suggests that one can study a game by examining its sum with other games. This leads to the concept of game equivalence.

Game Equivalence

If, for every game HH, the games G1+HG_1+H and G2+HG_2+H are either both losing or both winning, then G1G_1 and G2G_2 are said to be equivalent, written G1≈G2G_1\approx G_2.

It is easy to verify that this definition of ≈\approx is indeed an equivalence relation on all impartial games.

Sprague–Grundy Function

The analysis of Nim shows that distinct single-pile Nim games are not equivalent. However, every impartial game is equivalent to some single-pile Nim game. Thus, a number can be assigned to every impartial game; this is the Sprague–Grundy function.

To prove these results, we first establish two lemmas about game equivalence. The first says that adding a losing game to any game produces an equivalent game.

Lemma 1

For a game GG and any losing game A∈PA\in\mathcal P, we have G≈G+AG\approx G + A.

Proof

For every game HH, it suffices to prove that G+H≈G+A+HG+H\approx G+A+H.

If G+HG+H has a winning strategy, then G+A+HG+A+H also has one. If the opponent moves in subgame AA, make a move that restores it to a losing state; otherwise, follow the winning strategy in G+HG+H. This guarantees victory.

If G+HG+H is losing, then G+A+HG+A+H is also losing. Regardless of whether the move is made in subgame G+HG+H or subgame AA, the opponent can restore the relevant subgame to a losing state on the next turn. Therefore, the first player cannot win.

Second, two games are equivalent if and only if their sum is losing. This lemma provides a way to prove that two games are equivalent.

Lemma 2

Games GG and G′G' are equivalent if and only if G+G′∈PG+G'\in\mathcal P is a losing game.

Proof

If games GG and G′G' are equivalent, then G+G′G+G' and G+GG+G are either both winning or both losing, while G+GG+G is losing. Indeed, after any move by the first player, the second player can make the same move in the other subgame, so the first player eventually has no move.

Conversely, if G+G′G+G' is losing, Lemma 1 gives G≈G+(G+G′)=(G+G)+G′≈G′G\approx G+(G+G') = (G+G)+G' \approx G'.

These lemmas yield the following theorem:

Theorem (Sprague–Grundy)

For every finite impartial game GG, there exists n∈Nn\in\mathbf N such that G≈∗nG\approx *n.

Proof

We prove the theorem by mathematical induction. Let G={G1,G2,⋯ ,Gk}G = \{G_1,G_2,\cdots,G_k\}. By the induction hypothesis, there are n1,n2,⋯ ,nkn_1,n_2,\cdots,n_k such that Gi≈∗niG_i\approx *n_i. Consider the game

G′={∗n1,∗n2,⋯ ,∗nk}.G' = \{*n_1,*n_2,\cdots,*n_k\}.

We will prove that G′≈∗mG'\approx *m, where m=mex⁡{n1,n2,⋯ ,nk}m=\operatorname{mex}\{n_1,n_2,\cdots,n_k\} is the smallest natural number not in the set.

First, we show that G≈G′G\approx G'. By Lemma 2, it suffices to prove that G+G′G+G' is losing. Assume without loss of generality that G≠∗0G\neq *0. If the first player chooses GiG_i, the second player chooses ∗ni*n_i; conversely, if the first player chooses ∗ni*n_i, the second player chooses GiG_i. After these two moves, the game becomes Gi+∗niG_i+*n_i, which is losing by Lemma 2 and Gi≈∗niG_i\approx *n_i. Hence G≈G′G\approx G'.

Second, we show that G′≈∗mG'\approx*m. By Lemma 2, it suffices to prove that G′+∗mG'+*m is losing. Assume without loss of generality that G′≠∗0G'\neq *0. If the first player chooses ∗ni∈∗m*n_i\in *m, then by the definition of mm, the second player can choose ∗ni∈G′*n_i\in G', leaving the position ∗ni+∗ni∈P*n_i + *n_i\in\mathcal P, so the first player loses. If the first player chooses ∗ni∈G′*n_i\in G' with ni<mn_i<m, the second player can choose ∗ni∈∗m*n_i\in *m, again leaving ∗ni+∗ni∈P*n_i+*n_i\in\mathcal P, so the first player loses. Finally, if the first player chooses ∗ni∈G′*n_i\in G' with ni>mn_i>m, the second player can choose ∗m∈∗ni*m\in *n_i, leaving ∗m+∗m∈P*m+*m\in\mathcal P, so the first player loses. This proves G′≈∗mG'\approx *m.

By transitivity of equivalence, G≈∗mG\approx *m. This completes the induction and proves that every game GG is equivalent to a single-pile Nim game.

This result shows that each impartial game GG can be assigned a natural number nn such that G≈∗nG\approx *n.

Nimbers

The nimber of an impartial game GG is the unique natural number for which G≈∗nG\approx *n holds; this number is nn.

The function mapping each impartial game to its nimber is called the Sprague–Grundy function (also called the SG function), denoted by SG⁡(⋅)\operatorname{SG}(\cdot). Since every state of an impartial game is itself another impartial game, the corresponding nimber, or SG value, can be computed for every state of an impartial game.

The proof of the theorem in this section shows that the Sprague–Grundy function can be computed recursively as follows:

Corollary

For an impartial game GG, a state xx in it has Sprague–Grundy value SG⁡(x)\operatorname{SG}(x) satisfies

SG⁡(x)=mex⁡{SG⁡(x′):x′∈x}.\operatorname{SG}(x) = \operatorname{mex}\{\operatorname{SG}(x'): x'\in x\}.

Here, mex⁡(A):=min⁡{n∈N:n∉A}\operatorname{mex}(A):=\min\{n\in\mathbf N:n\notin A\} is the smallest natural number not appearing in set AA.

In other words, the SG value of a state is the mex⁡\operatorname{mex} of the SG values of all its successors.

The SG value (that is, the nimber) can be used to determine whether a state is winning for the first player.

Corollary

For an impartial game GG, a state xx is winning for the first player if and only if SG⁡(x)≠0\operatorname{SG}(x)\neq 0.

Finally, the SG value of a game sum is the Nim sum (that is, XOR) of the SG values of the component games.

Theorem (Sprague–Grundy)

For impartial games G1,G2,⋯ ,GnG_1,G_2,\cdots,G_n,

SG⁡(G1+G2+⋯+Gn)=SG⁡(G1)⊕SG⁡(G2)⊕⋯⊕SG⁡(Gn).\operatorname{SG}(G_1+ G_2+\cdots + G_n) = \operatorname{SG}(G_1)\oplus \operatorname{SG}(G_2)\oplus\cdots\oplus\operatorname{SG}(G_n).
Proof

Since ∗a1+∗a2+⋯+∗an*a_1+ *a_2 + \cdots + *a_n is the Nim game with pile sizes (a1,a2,⋯ ,an)(a_1,a_2,\cdots,a_n), the result for Nim shows that the game

∗a1+∗a2+⋯+∗an+∗(a1⊕a2⊕⋯⊕an)*a_1+ *a_2 + \cdots + *a_n + *(a_1\oplus a_2\oplus\cdots\oplus a_n)

is losing for the first player. By Lemma 2, we have

∗a1+∗a2+⋯+∗an≈∗(a1⊕a2⊕⋯⊕an).*a_1+ *a_2 + \cdots + *a_n \approx *(a_1\oplus a_2\oplus\cdots\oplus a_n).

Therefore,

SG⁡(∗a1+∗a2+⋯+∗an)=a1⊕a2⊕⋯⊕an.\operatorname{SG}(*a_1 + *a_2 + \cdots + *a_n) = a_1\oplus a_2\oplus\cdots\oplus a_n.

Set ai=SG⁡(Gi)a_i=\operatorname{SG}(G_i). Then Gi≈∗aiG_i\approx *a_i, and the algebraic properties of ≈\approx give

(G1+G2+⋯+Gn)+(∗a1+∗a2+⋯+∗an)=∑i=1n(Gi+∗ai)∈P.(G_1+ G_2+\cdots + G_n) + (*a_1 + *a_2 + \cdots + *a_n) = \sum_{i=1}^n(G_i+*a_i) \in\mathcal P.

Hence,

SG⁡(G1+G2+⋯+Gn)=SG⁡(∗a1+∗a2+⋯+∗an)=a1⊕a2⊕⋯⊕an=SG⁡(G1)⊕SG⁡(G2)⊕⋯⊕SG⁡(Gn).\begin{aligned} \operatorname{SG}(G_1+ G_2+\cdots + G_n) &= \operatorname{SG}(*a_1 + *a_2 + \cdots + *a_n) \\ &= a_1\oplus a_2\oplus \cdots \oplus a_n \\ &= \operatorname{SG}(G_1)\oplus \operatorname{SG}(G_2)\oplus\cdots\oplus\operatorname{SG}(G_n). \end{aligned}

This theorem greatly simplifies the computation of the SG value of a game sum.

The computation of SG values can therefore be summarized as follows:

  • For several independent games, compute their SG values separately and then take their Nim sum;
  • For a single game, the SG value of each state is the mex⁡\operatorname{mex} of the SG values of all its successors;
  • In particular, the SG value of a terminal state (one with no successors) is mex⁡∅=0\operatorname{mex}\varnothing = 0.

Nimbers

Every impartial game corresponds uniquely to a nimber. The set of finite nimbers is the set of natural numbers N\mathbf N. However, its algebraic properties differ from those of the natural numbers. More specifically, two operations can be defined on nimbers: the Nim sum ⊕\oplus and the Nim product ⊗\otimes:

Operations on Nimbers

For nimbers a,ba,b, define:

  • Nim sum a⊕b=mex⁡({a′⊕b:a′−Nim积a\oplus b=\operatorname{mex}(\{a'\oplus b:a' - Nim 积 a\otimes b=\operatorname{mex}({(a'\otimes b)\oplus(a\otimes b')\oplus(a'\otimes b'):a' [!info]+ How to Prove the Conclusions in This Section

The proofs of the conclusions in this section are all verification-based. For each game, a conclusion describes its first-player-losing and first-player-winning states. The proof only needs to verify that a first-player-losing state can lead only to a first-player-winning state, while a first-player-winning state always has at least one move to a first-player-losing state. To rewrite these proofs rigorously, one would first construct the game graph and then apply mathematical induction to the states in the graph; these verification steps are precisely the induction step.

Bachet Game

Compared with single-pile Nim, the Bachet game limits the number of stones that may be removed on each turn.

Bachet Game

There is one pile containing nn stones. Two players take turns removing at least 11 and at most kk stones. The player who removes the last stone wins.

The following result holds:

Theorem

The first player loses if and only if n≡0(modk+1)n\equiv 0\pmod {k+1}.

Proof 1

When n≢0(modk+1)n\not\equiv 0\pmod {k+1}, removing n mod (k+1)∈[1,k]n\bmod{(k+1)}\in[1,k] stones leaves the opponent in a losing state. Thus, the current state is winning for the first player.

Conversely, when n≡0(modk+1)n\equiv 0\pmod {k+1}, there is either no move, or after the first player removes k′k' stones, the opponent can immediately remove k+1−k′k+1-k' stones and return the game to a losing state.

Proof 2

As an application of the Sprague–Grundy theorem, let f(n)f(n) be the SG value of the position with nn stones remaining.

For n≤kn\le k, induction gives f(n)=nf(n)=n. This is the same as a single-pile Nim game because the limit on the number of stones removed is not active. For n>kn>k, we can prove that f(n)=n mod (k+1)f(n)=n\bmod{(k+1)}, and hence

f(n)=mex⁡{f(n−k),f(n−k+1),⋯ ,f(n−1)}.f(n) = \operatorname{mex}\{f(n-k),f(n-k+1),\cdots,f(n-1)\}.

These values contain every residue modulo k+1k+1 except n mod (k+1)n\bmod{(k+1)}. Therefore, f(n)=n mod (k+1)f(n) = n\bmod{(k+1)}.

Moore's Nim-k Game

Unlike Nim, Moore's Nim-kk game allows a move to remove stones from as many as kk piles at once.

Moore's Nim-kk Game

There are nn piles of stones. The ii-th pile contains aia_i stones. Two players take turns removing any positive number of stones from at least 11 and at most kk piles. The player who removes the last stone wins.

The following result holds:

Theorem

Write the size of each pile in binary. For every bit position dd, count the number of piles whose size has bit dd equal to 11, and take that count modulo (k+1)(k+1). If the remainder is 00 at every bit position, the first player loses; otherwise, the first player wins.

Proof

The proof is analogous to the proof for Nim. Let dd be the highest binary bit whose remainder is not 00, and let the corresponding remainder be k′≤kk'\le k. The winning strategy is to choose, among the piles whose bit dd is 11, kk piles and remove carefully chosen numbers of stones so that every bit-position remainder in the resulting position is 00. The only point requiring explanation is why the final choices of removed amounts are always possible.

In fact, after choosing the k′k' piles, removing 2d2^d stones from each makes the remainder at bit dd equal to 00. For lower bit positions, the remainders can be distributed arbitrarily among the chosen piles.

Staircase Nim

Staircase Nim is slightly more complicated: it allows stones to move between adjacent piles.

Staircase Nim

There are nn piles of stones. The ii-th pile contains aia_i stones. Two players take turns. On each turn, a player either removes any positive number of stones from pile 11, or moves any positive number of stones from pile i>1i>1 to pile i−1i-1. Removing the last stone wins the game.

The following result holds:

Theorem

The first player loses if and only if the Nim sum of the odd-indexed pile sizes, a1⊕a3⊕⋯⊕an−1+(n mod 2)=0a_1\oplus a_3\oplus\cdots\oplus a_{n-1+(n\bmod 2)}=0.

Proof

Whenever a player moves stones from an even-indexed pile to an odd-indexed pile, the opponent can continue moving those stones to the next even-indexed pile (or remove them), so this move does not affect the odd-indexed-pile position. Each odd-indexed pile can then be viewed as an independent single-pile Nim game whose stones move down to the adjacent even-indexed pile (or are removed). By the Sprague–Grundy theorem for game sums, the SG value of Staircase Nim is the Nim sum of the SG values of these subgames. This gives the stated result.

Fibonacci Nim

Fibonacci Nim is similar to Bachet's game: there is one pile, and the number of stones that may be removed is restricted. Unlike Bachet's game, the restriction in Fibonacci Nim changes dynamically.

Fibonacci Nim

There is one pile containing nn stones. The first player may remove any number of stones, but may not remove the entire pile. Thereafter, the number removed on each turn may not exceed twice the number removed on the previous turn (that is, the opponent's turn). The number removed on every turn must not be 00 and must be positive. The player who removes the last stone wins.

The following result holds:

Theorem

At the start of the game, the first player loses if and only if the number of stones nn is a Fibonacci number.

Proof

Let qq be the quota, the maximum number of stones that may be removed in the current position. On the first turn, q=n−1q=n-1; thereafter, qq is twice the number of stones removed on the previous turn. Consider the Fibonacci representation of the remaining number of stones nn, namely, the unique decomposition of nn into a sum of positive, nonconsecutive Fibonacci numbers. We prove that the current state is winning if and only if qq is at least the smallest Fibonacci number in the decomposition of nn.

The winning strategy is to remove all remaining stones if possible; otherwise, remove the smallest Fibonacci number in the decomposition. Since the next-smallest Fibonacci number in the decomposition is strictly greater than twice the smallest one, whenever a winning player cannot remove all the stones, the opponent cannot remove that next-smallest Fibonacci number on the following turn (which becomes the smallest Fibonacci number then), and therefore faces a losing state.

Conversely, suppose the current state is losing, and let the number removed on the current turn be kk. It is strictly smaller than the smallest Fibonacci number FF in the current decomposition. If F′F' is the smallest Fibonacci number in the next position, it is also the smallest Fibonacci number in the decomposition of F−kF - k. Write F′=F′′+F′′′F'=F''+F''' with F′′>F′′′F''>F''', that is, F′′′,F′′,F′F''',F'',F' are three consecutive Fibonacci numbers. If k<F′′k<F'', adding k+(F−k)k + (F-k) in Fibonacci representation requires no carry and therefore cannot produce FF. Thus, k≥F′′k\ge F''. Hence, the next-turn quota 2k>F′′+F′′′=F′2k>F''+F'''=F' is a winning state.

Wythoff Game

Wythoff's game allows stones to be removed from multiple piles simultaneously, but requires the same number of stones to be removed from every affected pile.

Wythoff Game

There are two piles containing a1a_1 and a2a_2 stones, respectively. Two players take turns removing stones from either one pile or both piles. A move must remove at least one stone; if stones are removed from both piles, the same number must be removed from each. The player who removes the last stone wins.

The following result holds:

Theorem

Assume without loss of generality that a1≤a2a_1\le a_2. Then the first player loses if and only if a1=⌊(a2−a1)ϕ⌋a_1 = \lfloor(a_2-a_1)\phi\rfloor, where ϕ=(5+1)/2\phi=(\sqrt{5}+1)/2 is the golden ratio.

The following lemma is needed to prove this result:

Beatty Sequence

Let r>1r > 1 be irrational. The Beatty sequence it generates is Br={⌊kr⌋:k∈N+}\mathcal B_r = \{\lfloor kr\rfloor : k \in\mathbf N_+\}.

Rayleigh's Theorem

Let r,s>1r,s > 1 be irrational numbers satisfying 1r+1s=1\dfrac{1}{r}+\dfrac{1}{s}=1. Then the sequences Br\mathcal B_r and Bs\mathcal B_s form a partition of the positive integers N+\mathbf N_+. They are then called complementary Beatty sequences.

Proof

Let Ar={kr:k∈N+}\mathcal A_r=\{kr:k\in\mathbf N_+\}. Sort the elements of A=Ar∪Aℓ\mathcal A=\mathcal A_r\cup\mathcal A_\ell into a sequence {ai}i∈N+\{a_i\}_{i\in\mathbf N_+}. It suffices to prove that i=⌊ai⌋i=\lfloor a_i\rfloor for every i∈N+i\in\mathbf N_+; this gives that Br∪Bs\mathcal B_r\cup\mathcal B_s is a partition of the positive integers N+\mathbf N_+.

First, prove that no element is repeated in the sequence. Otherwise, there would be k,ℓ∈N+k,\ell\in\mathbf N_+ with kr=ℓskr=\ell s. Then

ℓk=rs=r−1.\dfrac{\ell}{k} = \dfrac{r}{s} = r - 1.

The left side is rational, while the right side is irrational, a contradiction. Thus, all numbers in the sequence are distinct.

Next, prove that the number of elements of A\mathcal A not exceeding aia_i is exactly ⌊ai⌋\lfloor a_i\rfloor. Assume without loss of generality that ai∈Ara_i\in\mathcal A_r, so ai=kra_i=kr. Counting the elements of Ar\mathcal A_r and Aℓ\mathcal A_\ell separately, the number of positive integers not exceeding aia_i is

k+⌊krs⌋=k+⌊k(r−1)⌋=⌊kr⌋=⌊ai⌋k + \left\lfloor\dfrac{kr}{s}\right\rfloor = k + \lfloor k(r-1)\rfloor = \lfloor kr\rfloor = \lfloor a_i\rfloor

Thus, since {ai}\{a_i\} is strictly increasing, the number of values not exceeding aia_i is exactly ii. Therefore, i=⌊ai⌋i=\lfloor a_i\rfloor.

This proves the result stated above.

Proof of the Wythoff Game Result

For every state with a1<a2a_1 < a_2 that is losing, write it as (a1,a2)(a_1,a_2) and let k=a2−a1∈N+k = a_2 - a_1 \in\mathbf N_+. Then a1=⌊kϕ⌋a_1=\lfloor k\phi\rfloor and a2=⌊k(ϕ+1)⌋a_2=\lfloor k(\phi+1)\rfloor. Since ϕ\phi is the golden ratio, 1ϕ+1ϕ+1=1\dfrac{1}{\phi}+\dfrac{1}{\phi+1}=1. Rayleigh's theorem shows that the sequences {⌊kϕ⌋}\{\lfloor k\phi\rfloor\} and ⌊k(ϕ+1)⌋\lfloor k(\phi+1)\rfloor form a partition of the positive integers N+\mathbf N_+. This means that among all losing states with a1<a2a_1 < a_2, written (a1,a2)(a_1,a_2), the components a1a_1 and a2a_2 each take every positive integer exactly once, and their difference a2−a1a_2-a_1 also takes every positive integer exactly once.

A legal move in Wythoff's game either keeps one component fixed or keeps the difference fixed. Therefore, no legal move from a losing state can reach another losing state. Conversely, consider any winning state (a1,a2)(a_1,a_2) and assume without loss of generality that a1≤a2a_1\le a_2, with k=a2−a1k=a_2-a_1. If a1>⌊kϕ⌋a_1>\lfloor k\phi\rfloor, the first player can remove (a1−⌊kϕ⌋)(a_1 - \lfloor k\phi\rfloor) stones from each pile and reach a losing position. Conversely, by the preceding paragraph, for this value of a1a_1, there is a unique losing state (a1,a2′)(a_1,a_2'). If a1>a2′a_1 > a_2', then clearly a2′<a2a_2' < a_2; otherwise, if a1<a2′a_1 < a_2', choose k′=a2′−a1k'=a_2'-a_1 so that a1=⌊k′ϕ⌋a_1=\lfloor k'\phi\rfloor. Since a1<⌊kϕ⌋a_1 < \lfloor k\phi\rfloor, we have k′<kk' < k, and therefore a2′=a1+k′<a1+k=a2a_2'=a_1 + k' < a_1+k = a_2. Thus, whenever a1<⌊kϕ⌋a_1 < \lfloor k\phi\rfloor, we have a2′<a2a_2' < a_2, and the first player can remove (a2−a2′)(a_2-a'_2) stones from the second pile to reach a losing state.

Coin-Turning Game

Coin-turning games are another common class of impartial combinatorial games.

Coin-Turning Game

Let (S,⪯)(S,\preceq) be a well-founded partially ordered set, and let the map f:S→PPSf:S\rightarrow\mathcal P\mathcal PS satisfy the following conditions: For every s∈Ss\in S, the set f(s)f(s) is nonempty; for every T∈f(s)T\in f(s), we have s∈Ts\in T; and for every t∈Tt\in T, t⪯st\preceq s. At every element of SS there is a coin, which may be heads-up or tails-up. Players take turns choosing a heads-up coin ss and a set T∈f(s)T\in f(s), then flipping all coins in TT. The player who turns all coins tails-up wins.

Coin-turning games are actually a large family of games. Their particular form depends on the chosen partially ordered set SS and map ff. The conditions on ff in the game definition say that whenever a player chooses a set TT to flip, there is a heads-up coin ss in TT such that every element of it precedes ss. This guarantees that the game terminates after finitely many moves.

Examples
  1. Let S={1,2,⋯ ,n}S=\{1,2,\cdots,n\} and f(s)={{t,s}:t≤s}f(s)=\{\{t,s\}:t \le s\}. This is a row of nn coins; on each move, a player flips a heads-up coin and may also choose a coin to its left to flip.
  2. Let S={1,2,⋯ ,n}S=\{1,2,\cdots,n\} and f(s)={[t,s]:t≤s}f(s)=\{[t,s]:t \le s\}. This is a row of nn coins; on each move, a player flips a contiguous interval, but the rightmost coin in that interval must have been heads-up before the move.
  3. Let S={1,2,⋯ ,n}2S=\{1,2,\cdots,n\}^2 and f(s)={{s}}f(s)=\{\{s\}\}. This is an nn-by-nn grid of coins; on each move, a player may flip only one heads-up coin.
  4. Let SS be the set of vertices of a rooted tree, and let f(s)f(s) be the family of all subsets containing ss itself among the subsets of the vertices on the path from vertex ss to the root. This is a rooted tree with one coin at each node; on each move, a player flips a heads-up coin and may choose several coins at its ancestors to flip.

Although coin-turning games come in many forms, their solution method is the same. For a coin-turning game (S,f)(S,f), let GsG_s be the position in which only the coin at element ss is heads-up. These positions are called basic positions. Every position GG can then be viewed as the sum of the games corresponding to these basic positions. In other words, the following theorem holds:

Theorem

For a coin-turning game (S,f)(S,f) and a position GG, let H(G)⊆SH(G)\subseteq S be the set of locations of the heads-up coins. Then the SG value of GG is

SG⁡(G)=⨁s∈H(G)SG⁡(Gs).\operatorname{SG}(G) = \bigoplus_{s\in H(G)}\operatorname{SG}(G_s).
Proof

Consider a related game: in a position G′G', several stones may be placed at each element of SS. On each move, a player may remove one stone at ss, choose a set T∈f(s)T\in f(s), and place one stone at every element of T∖{s}T\setminus\{s\}. For this game, define the basic position Gs′G'_s as the position with one stone only at ss. Every position in this game is the sum of the basic positions corresponding to all its stones. Indeed, when a new stone is placed, associate it with the stone that was removed. Then every stone arising during the game can be associated with one of the stones in the initial position, and the subgames corresponding to distinct initial stones do not interfere with one another. The entire game is therefore their sum. Since stones at the same location have the same basic-position SG value, the XOR property shows that the SG value of G′G' depends only on the parity of the number of stones in each pile, not on their exact counts. Thus, for the position G′G', let the set of positions with an odd number of stones be H(G′)H(G'); this analysis gives

SG⁡(G′)=⨁s∈H(G′)SG⁡(Gs′).\operatorname{SG}(G') = \bigoplus_{s\in H(G')} \operatorname{SG}(G'_s).

It remains only to establish the equivalence of G′G' and GG.

For a position G′G' of the new game and a position GG of the coin-turning game, if the locations with an odd number of stones in G′G' are exactly the locations of the heads-up coins in GG, then G′G' and GG are equivalent. By Lemma 2 of the Sprague–Grundy theorem, this is equivalent to proving that G+G′G+G' is losing. The second player has a simple winning strategy: if the first player removes a stone at ss and there is more than one stone there, the second player directly imitates the move; otherwise, the second player chooses the same ss and T∈f(s)T\in f(s) as the first player, but acts in the other subgame: if the first player removes a stone, the second player flips coins, and if the first player flips coins, the second player removes stones. Whatever the first player does, the second player can continue responding while preserving the condition that the positions with an odd number of stones coincide with the heads-up coins. Thus the game must end when the first player has no legal move, so the first player loses. This proves the theorem.

By this result, to determine whether a position is winning, we only need to compute the SG values of the basic positions corresponding to its heads-up coins and take their Nim sum. These basic-position SG values are also easy to compute, because their successor positions are specified by ff, and the SG values of successor positions can be obtained inductively:

SG⁡(Gs)=mex⁡T∈f(s)⨁t∈T∖{s}SG⁡(Gt).\operatorname{SG}(G_s) = \operatorname{mex}\limits_{T\in f(s)}\bigoplus_{t\in T\setminus\{s\}}\operatorname{SG}(G_t).

This provides a recurrence for the SG values of the basic positions.

Bipartite Graph Game

Prior knowledge: Maximum Matching in Bipartite Graphs

As the final topic of this section, we discuss the bipartite graph game. Although this game is commonly called a bipartite graph game, neither its description nor the proof of its result depends on the structure of a bipartite graph, so the result actually holds for general undirected graphs. However, maximum matching is more complicated in general graphs, so this result usually appears in problems about bipartite graphs.

Bipartite Graph Game

Two players take turns. Each player’s position consists of an undirected graph G=(V,E)G=(V,E) and a vertex v∈Vv\in V. On a turn, when the current position is (G,v)(G,v), the player must choose a vertex adjacent to vv, call it uu. The vertex vv and all its incident edges are then deleted from GG, leaving a residual graph G′G'. The new position (G′,u)(G',u) is passed to the next player. If, at the start of a turn, the current vertex vv has no adjacent vertex in the graph (that is, there is no legal choice), the player cannot move and loses the game.

The following result holds:

Theorem

The first player wins if and only if vertex vv is an essential vertex of graph GG's maximum matching; that is, in every maximum matching of graph GG, vertex vv is matched.

Proof

First suppose that vertex vv is an essential vertex of a maximum matching of GG. Let GG have a maximum matching MM. The first player can move to the vertex in MM matched with vertex vv, namely uu. Since vv appears in every maximum matching of GG, the size of a maximum matching of the residual graph G′G' is at most ∣M∣−1|M|-1. After removing MM's edge (v,v)(v,v), we obtain in G′G' a matching of size ∣M∣−1|M|-1, denoted M′M'; together these two facts show that M′M' is a maximum matching of G′G'. In the position faced by the second player, vertex uu is not matched by M′M'. Therefore, the second player is in a losing state.

Conversely, suppose there is a maximum matching MM in which vv is unmatched. Since MM is maximum, every vertex adjacent to vv must be matched; otherwise, adding the edge between them to MM would produce a larger matching. Therefore, regardless of the first player’s choice, the second player is in a winning state.

For an algorithm to find essential vertices of a maximum matching in a bipartite graph, see the maximum matching in bipartite graphs page.

There is also a variant of the bipartite graph game:

Variant of the Bipartite Graph Game

Let G=(V,E)G=(V,E) be an undirected graph with one stone placed at every vertex. Two players take turns removing stones. On the first turn, the first player may remove any stone; on later turns, the vertex from which a player removes a stone must be adjacent to the vertex from which the opponent removed a stone on the preceding turn. The first player who cannot remove a stone loses.

Clearly, this variant is equivalent to the bipartite graph game described above with the first player choosing the initial position, after which the bipartite graph game begins with the second player. Thus, in this variant, the first player loses if and only if every vertex is an essential vertex of a maximum matching, that is, if graph GG has a perfect matching.

Misère Nim

This section discusses how to solve misère Nim.

Nim Game

There are nn piles of stones. The ii-th pile contains aia_i stones. Two players take turns removing any positive number of stones from any one pile. The player who removes the last stone loses.

The following result holds:

Theorem

In misère Nim, the state (a1,a2,⋯ ,an)(a_1,a_2,\cdots,a_n) is losing P\mathcal P if and only if either

  1. Some ii satisfies ai>1a_i>1 and the Nim sum a1⊕a2⊕⋯⊕an=0a_1\oplus a_2\oplus\cdots\oplus a_n=0, or
  2. For every ii, we have ai≤1a_i\le 1, and the number of nonempty piles is odd.
Proof

Since having no legal move is a winning state N\mathcal N, induction shows that when every pile contains only one stone, an odd number of piles corresponds to a first-player-losing state N\mathcal N, while an even number of piles corresponds to a first-player-winning state N\mathcal N.

Next, consider positions in which some piles contain strictly more than 11 stone.

Case A: If only one pile contains more than 11 stone, then the Nim sum is necessarily not 00. Moreover, the first player can move to a position in which every pile contains at most 11 stone and can control the parity of the number of nonempty piles. Thus, this is a first-player-winning state N\mathcal N.

Case B: Now suppose more than one pile contains more than 11 stone. Whatever move is made, the next position still has at least one pile containing more than 11 stone. By the induction hypothesis, a first-player-losing next position corresponds to a zero Nim sum, while a first-player-winning next position corresponds to a nonzero Nim sum. This is exactly the same induction hypothesis as in normal Nim. Repeating the argument for Nim shows that the current position also follows the rule that a zero Nim sum corresponds to a first-player-losing state.

Directed Graph Games

The impartial combinatorial games discussed in this article require that the same position never occur twice and that a draw be impossible. Therefore, their game graphs are always directed acyclic graphs. This section relaxes that restriction and discusses how to classify states as first-player winning, first-player losing, or drawn on a general directed graph.

The rules of a directed graph game are broadly the same as those of other impartial combinatorial games: starting from the initial state, the players take turns moving along a directed edge until no move is available. Under normal play, the last player unable to move loses; under misère play, that player wins. Thus, each state has one of three possible outcomes: first-player win, first-player loss, or draw. In a draw, the game never terminates. Although the situation is slightly more complicated, the lemma about losing and winning states still holds, and all remaining states are drawn:

  • A state is winning for the first player if and only if one of its successors is losing;
  • If a state has successors, it is losing for the first player if and only if all of its successors are winning;
  • A state that cannot be classified as winning or losing is drawn.

To classify all states into these three categories, one can use an approach similar to topological sorting:

  1. During initialization, record the out-degree of every state, enqueue every state with out-degree zero, and mark it as losing or winning according as the game uses normal or misère play.
  2. Pop the state at the front of the queue. If it is losing, mark its predecessors as winning. Otherwise, the current state is winning: decrement the out-degree of every predecessor, and mark any predecessor whose out-degree becomes zero as losing. Enqueue every predecessor whose outcome can now be determined as winning or losing.
  3. Stop when the queue is empty. Every state not yet classified as winning or losing is drawn.

This algorithm classifies all states in O(∣V∣+∣E∣)O(|V|+|E|) time.

Example Problems

This section discusses several typical example problems.

Luogu P2148 [SDOI2009] E&D

There are 2n2n piles of stones. For each k=1,2,⋯ ,nk=1,2,\cdots,n, piles 2k−12k-1 and 2k2k form a group. The players take turns choosing a group of piles, removing one of its piles, and splitting the other pile into two nonempty piles placed at the two positions of that group. If every pile contains only one stone, the current player has no legal move and loses. Given the number of stones {ai}i=12n\{a_i\}_{i=1}^{2n} in each pile, determine whether the position is winning for the first player.

Solution

The games for different groups of piles are clearly independent. Therefore, it suffices to compute the SG value of each group, then compute the SG value of the whole game and determine whether it is winning. The key is how to compute the SG value of one group. This is not easy. A common approach to game-theoretic problems of this kind is to generate a table. Let the two piles in a group contain (i,j)(i,j) stones, respectively, and let the SG value be f(i,j)f(i,j). A brute-force table-generating program gives the following result:

0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 
1 1 2 2 1 1 3 3 1 1 2 2 1 1 4 4
0 2 0 2 0 3 0 3 0 2 0 2 0 4 0 4
2 2 2 2 3 3 3 3 2 2 2 2 4 4 4 4
0 1 0 3 0 1 0 3 0 1 0 4 0 1 0 4
1 1 3 3 1 1 3 3 1 1 4 4 1 1 4 4
0 3 0 3 0 3 0 3 0 4 0 4 0 4 0 4
3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 4
1 1 2 2 1 1 4 4 1 1 2 2 1 1 4 4
0 2 0 2 0 4 0 4 0 2 0 2 0 4 0 4
2 2 2 2 4 4 4 4 2 2 2 2 4 4 4 4
0 1 0 4 0 1 0 4 0 1 0 4 0 1 0 4
1 1 4 4 1 1 4 4 1 1 4 4 1 1 4 4
0 4 0 4 0 4 0 4 0 4 0 4 0 4 0 4
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4

The table has a strong pattern. Notice that it is divided into several 2×22\times 2 matrices, with 00 always in the upper-left corner and the other three entries always equal. We may therefore compress the table by replacing each 2×22\times 2 matrix with the common value outside its upper-left corner:

1 2 1 3 1 2 1 4 
2 2 3 3 2 2 4 4 
1 3 1 3 1 4 1 4 
3 3 3 3 4 4 4 4 
1 2 1 4 1 2 1 4 
2 2 4 4 2 2 4 4 
1 4 1 4 1 4 1 4 
4 4 4 4 4 4 4 4 

The compressed table is the value at the same position in the complete table plus one. The problem is essentially solved. With indices starting from 00, the value at (i,j)(i,j) in the table, denoted by g(i,j)g(i,j), is given by

g(i,j)={0,if 2∣i and 2∣j,g(⌊i/2⌋,⌊j/2⌋)+1,otherwise.g(i,j) = \begin{cases} 0, & \text{if }2\mid i\text{ and }2\mid j,\\ g(\lfloor i/2\rfloor,\lfloor j/2\rfloor)+1,& \text{otherwise}. \end{cases}

The required SG function is f(i,j)=g(i−1,j−1)f(i,j)=g(i-1,j-1). Using this recurrence, the algorithm runs in O(log⁡min⁡{i,j})O(\log\min\{i,j\}) time to compute f(i,j)f(i,j).

A simple induction also shows that g(i,j)g(i,j) is the minimum number of times one must repeatedly divide ii and jj by 22 simultaneously to obtain two even numbers. Equivalently, form the bitwise OR of ii and jj; the number of its trailing bits equal to 11 is the same. Thus, the value can be computed directly using __builtin_ctz(~(i | j)).

In problems of this kind, once a table observation yields an SG expression, it is usually easy to prove the expression by induction. The key to solving the problem is therefore to obtain the result in some form, rather than to derive it from scratch. For example, once the result is known, the recurrence in this problem can be proved inductively as follows. Let SkS_k be the set of SG values of the positions obtained by splitting kk stones into two nonempty piles. Then f(i,j)=mex⁡(Si∪Sj)f(i,j) = \operatorname{mex}(S_i \cup S_j), so SkS_k satisfies the recurrence

Sk={mex⁡(Si∪Sj):i+j=k, i,j∈N+}.S_k = \{\operatorname{mex}(S_i \cup S_j) : i + j = k,~i,j\in\mathbf N_+\}.

We need to prove that d∈Skd\in S_k if and only if the binary representation of (k−1)(k-1) has bit dd (the lowest bit is bit 00) equal to 11.

Use mathematical induction. The base case S1=∅S_1=\varnothing is immediate. Assume the statement holds for every positive integer smaller than kk. Then d∈Skd\in S_k if and only if there exist i,j∈N+i,j\in\mathbf N_+ such that i+j=ki+j=k, at least one of the bits of (i−1)(i-1) and (j−1)(j-1) at positions d′<dd' < d is 11, and both bit dd values are 00. Clearly, such a split exists if and only if, considering only bits 0∼d0\sim d, namely modulo 2d+12^{d+1}, the value of (k−1)=(i−1)+(j−1)+1(k-1)=(i-1)+(j-1)+1 lies in the interval [2d,2d+1−1)[2^d,2^{d+1}-1). This condition is equivalent to (k−1)(k-1) having bit dd equal to 11. The induction step follows, and the proposition is proved.

Reference Code
#include <iostream>
#include <vector>

int g(int i, int j) {
  return i % 2 == 0 && j % 2 == 0 ? 0 : g(i / 2, j / 2) + 1;
}

int f(int i, int j) { return g(i - 1, j - 1); }

int main() {
  int t;
  std::cin >> t;
  for (; t; --t) {
    int n;
    std::cin >> n;
    int v = 0;
    for (int i = 0; i < n / 2; ++i) {
      int x, y;
      std::cin >> x >> y;
      v ^= f(x, y);
    }
    std::cout << (v ? "YES" : "NO") << '\n';
  }
  return 0;
}
Luogu P5675 [GZOI2017] Stone-Taking Game

There are nn piles of stones, and the ii-th pile contains aia_i stones. The two players play Nim. One may now arbitrarily designate several piles as the initial position and designate one of them from which the first player must remove stones on the first turn, without specifying how many stones to remove. How many designations make it impossible for the first player to win? The data satisfy n,ai≤200n,a_i\le 200.

Solution

For this type of problem, one must use results about common games together with other knowledge. Suppose the first player is required to remove stones from pile ii, and the Nim sum of all designated piles is vv. Then the first player cannot win if and only if ai≤ai⊕va_i \le a_i\oplus v; in other words, the number of stones in pile ii, namely aia_i, does not exceed the Nim sum of all piles except pile ii, namely ai⊕va_i\oplus v. Since the data range is small, enumerate directly the pile designated for the first-turn move. When enumerating pile ii, each remaining pile may be selected or not selected; the numbers of ways to obtain each distinct Nim sum can be computed by DP, and it suffices to sum the counts whose final Nim sum is at least aia_i.

Reference Code
#include <array>
#include <iostream>
#include <vector>

int main() {
  constexpr int M = 1e9 + 7;
  constexpr int L = 256;
  int n;
  std::cin >> n;
  std::vector<int> a(n);
  for (auto& x : a) std::cin >> x;
  int res = 0;
  for (int i = 0; i < n; ++i) {
    std::array<int, L> dp = {};
    dp[0] = 1;
    for (int j = 0; j < n; ++j) {
      if (j == i) continue;
      std::array<int, L> _dp = {};
      for (int v = 0; v < L; ++v) {
        _dp[v] = (dp[v] + dp[v ^ a[j]]) % M;
      }
      dp = std::move(_dp);
    }
    for (int v = a[i]; v < L; ++v) {
      res = (res + dp[v]) % M;
    }
  }
  std::cout << res << std::endl;
  return 0;
}
Luogu P2599 [ZJOI2009] Stone-Taking Game

There are nn piles of stones, and the ii-th pile contains aia_i stones. The two players take turns removing stones. On each turn, they may choose one of the leftmost or rightmost two piles and remove any number of stones from it, but they may not remove zero stones. The player who removes the last stone wins. Determine whether the first player has a winning strategy.

Solution

Since this problem has no independent subgames, it fundamentally uses only the lemma for determining losing and winning states. Start with the simplest case. When n≤2n\le 2, this is Nim. When n≥3n \ge 3, the problem becomes more complicated. However, because only the two end piles can be operated on, let their numbers of stones be xx and yy, respectively. Further, let f(x,y)f(x,y) be the indicator of a first-player-winning state: f(x,y)=1f(x,y)=1 when the first player wins and f(x,y)=0f(x,y)=0 otherwise. It is easy to see that f(x,y)f(x,y) satisfies the recurrence f(x,y)=0f(x,y)=0 if and only if, for every s<xs < x and t<yt < y, we have f(x,t)=f(s,y)=1f(x,t)=f(s,y)=1. When x=0x=0 or y=0y=0, the game has fewer than nn piles and the numbers of the middle piles must be considered further. Therefore, temporarily assume that f(x,0)f(x,0) and f(0,y)f(0,y) are known, and consider how to derive all values of f(x,y)f(x,y) from them. This is not difficult. Consider an infinite matrix whose index set is N×N\mathbf N\times\mathbf N. Computing f(x,y)f(x,y) amounts to filling it with 00 and 11, under the conditions that each row and column contains at most one 00, and that if no earlier position in the same row or column has been 00, the position is 00. The positions of the 00s in each row define a function from row number xx to column number yy. After trying a few examples (that is, making a table), one finds that if the unique value satisfying f(x,0)=0f(x,0)=0 is the xx value x0x_0, and the unique value satisfying f(0,y)=0f(0,y)=0 is the yy value y0y_0, then, for every xx, the condition f(x,y)=0f(x,y)=0 holds when

y={0,x=x0,x−1,x0<x<y0,x+1,y0<x<x0,x,otherwise.y = \begin{cases} 0, & x = x_0,\\ x - 1, & x_0 < x < y_0,\\ x + 1, & y_0 < x < x_0,\\ x, & \text{otherwise}. \end{cases}

Thus, once x0x_0 and y0y_0 are known, any position can be computed in O(1)O(1) time, determining f(x,y)f(x,y) and whether the current state is winning for the first player. The values x0x_0 and y0y_0 can be computed recursively. For example, x0x_0 is the unique solution of f(x,0)=0f(x,0)=0, while the value of f(x,0)f(x,0) can be computed by removing the rightmost pile and considering only the remaining n−1n-1 piles; that is, considering only the first n−1n-1 piles, one can likewise compute f1,n−1(x,y)f_{1,n-1}(x,y), and evidently f(x,0)=f1,n−1(x,an−1)f(x,0)=f_{1,n-1}(x,a_{n-1}). Similarly, after removing the leftmost pile and computing f2,n(x,y)f_{2,n}(x,y), we obtain f(0,y)=f2,n(a1,y)f(0,y)=f_{2,n}(a_1,y). Of course, computing the inner functions f1,n−1(x,y)f_{1,n-1}(x,y) and f2,n(x,y)f_{2,n}(x,y) depends on functions for still smaller intervals. This is a typical interval DP. Each layer only needs to maintain the corresponding x0x_0 and y0y_0 values.

Reference Code
#include <array>
#include <iostream>
#include <vector>

int main() {
  // Transition helper as explained above.
  auto calc = [](int x0, int y0, int x) -> int {
    return x == x0 ? 0
                   : ((x < x0 && x < y0) || (x > x0 && x > y0)
                          ? x
                          : (x0 < y0 ? x - 1 : x + 1));
  };

  int t;
  std::cin >> t;
  for (; t; --t) {
    int n;
    std::cin >> n;
    std::vector<int> a(n);
    for (auto& x : a) std::cin >> x;

    // dp[i][j][0] = the unique value x such that
    //     f_{i-1,j}(x, a_j) = 0
    // i.e. the interval game [i, j] is in a P-position
    // when a pile of size x is attached to the LEFT.
    //
    // dp[i][j][1] = the unique value y such that
    //     f_{i,j+1}(a_i, y) = 0
    // i.e. the interval game [i, j] is in a P-position
    // when a pile of size y is attached to the RIGHT.
    std::vector<std::vector<std::array<int, 2>>> dp(
        n, std::vector<std::array<int, 2>>(n));

    // Base case: single-element interval [i, i].
    // The "left" and "right" pile values both equal a[i].
    for (int i = 0; i < n; ++i) dp[i][i][0] = dp[i][i][1] = a[i];

    // Build up intervals of increasing length d.
    for (int d = 1; d < n; ++d) {
      for (int i = 0; i + d < n; ++i) {
        dp[i][i + d][0] =
            calc(dp[i][i + d - 1][1], dp[i][i + d - 1][0], a[i + d]);
        dp[i][i + d][1] = calc(dp[i + 1][i + d][0], dp[i + 1][i + d][1], a[i]);
      }
    }

    // The original game corresponds to attaching nothing on the left.
    // It is a P-position if and only if the unique value y satisfying
    //     f_{-1, n-1}(0, y) = 0
    // is y = 0.
    std::cout << (dp[0][n - 1][0] != 0) << '\n';
  }
  return 0;
}

Exercises

First are some template problems. They are simple applications of the results on this page:

Then come some problems requiring stronger insight or more comprehensive techniques:

Finally, some bipartite graph game problems are listed separately because they require algorithms for bipartite graph matching:

References and Notes

Footnotes

  1. The names “N\mathcal N state” and “P\mathcal P state” respectively mean “Next player wins” and “Previous player wins”. ↩

  2. The “sums” discussed in this article are disjunctive sums under the long rule. This is the most common way to combine games. Other ways of combining games are also possible. For a detailed discussion, see Chapter 14 of Conway, John H. On numbers and games. AK Peters/CRC Press, 2000. ↩

This content comes from OI Wiki: Impartial Combinatorial Games. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.