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 piles of stones. The -th pile contains 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 piles containing stones, respectively. One may remove stones from pile , taking stones and giving the position ; one may also remove stones from pile , taking stones and giving . If at some point the position becomes , player A may remove the stones from pile , taking 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 piles containing stones can be drawn as follows:
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 and , 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:
- A state with no successor is a losing state ;
- A state is a winning state if and only if at least one of its successors is a losing state ;
- A state is a losing state if and only if all of its successors are winning states .
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 time, where is the number of states in the graph and 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 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 is defined as .
The Nim sum is simply the bitwise XOR operation.
Theorem
In Nim, the state is a losing state if and only if the Nim sum
Proof
Apply induction to all possible states:
-
If for every , the state has no successor and its Nim sum is , so the statement holds.
-
Suppose . 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 . By the properties of the Nim sum (that is, XOR), this is equivalent to finding a pile of size from which some stones can be removed so that its new size is , or equivalently, .
Let the highest bit of whose value is be bit . Then there must be some whose bit is . For the corresponding pile, we have , because in , bit is , while all higher bits are the same as in .
-
Suppose . 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 . This is immediate: every legal move changes to , so the Nim sum becomes .
Thus, the winning status of a Nim position can be determined in 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 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:
Here, and .
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 stones, it can be represented as
Here, the notation denotes the single-pile Nim game (or its initial state) with stones.
Example (continued)
With this notation, the states in the example above can be represented simply as
In the discussion that follows, the notation should be understood to mean that state is a successor of state .
Game Sums and Equivalence
The equivalence relation on games depends on the concept of the sum of games2.
Game Sum
For games and , their sum (or combined game) is denoted by and is the game
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, produces a losing game only when combined with another ; combined with any other game , 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 , the games and are either both losing or both winning, then and are said to be equivalent, written .
It is easy to verify that this definition of 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 and any losing game , we have .
Proof
For every game , it suffices to prove that .
If has a winning strategy, then also has one. If the opponent moves in subgame , make a move that restores it to a losing state; otherwise, follow the winning strategy in . This guarantees victory.
If is losing, then is also losing. Regardless of whether the move is made in subgame or subgame , 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 and are equivalent if and only if is a losing game.
Proof
If games and are equivalent, then and are either both winning or both losing, while 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 is losing, Lemma 1 gives .
These lemmas yield the following theorem:
Theorem (Sprague–Grundy)
For every finite impartial game , there exists such that .
Proof
We prove the theorem by mathematical induction. Let . By the induction hypothesis, there are such that . Consider the game
We will prove that , where is the smallest natural number not in the set.
First, we show that . By Lemma 2, it suffices to prove that is losing. Assume without loss of generality that . If the first player chooses , the second player chooses ; conversely, if the first player chooses , the second player chooses . After these two moves, the game becomes , which is losing by Lemma 2 and . Hence .
Second, we show that . By Lemma 2, it suffices to prove that is losing. Assume without loss of generality that . If the first player chooses , then by the definition of , the second player can choose , leaving the position , so the first player loses. If the first player chooses with , the second player can choose , again leaving , so the first player loses. Finally, if the first player chooses with , the second player can choose , leaving , so the first player loses. This proves .
By transitivity of equivalence, . This completes the induction and proves that every game is equivalent to a single-pile Nim game.
This result shows that each impartial game can be assigned a natural number such that .
Nimbers
The nimber of an impartial game is the unique natural number for which holds; this number is .
The function mapping each impartial game to its nimber is called the Sprague–Grundy function (also called the SG function), denoted by . 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 , a state in it has Sprague–Grundy value satisfies
Here, is the smallest natural number not appearing in set .
In other words, the SG value of a state is the 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 , a state is winning for the first player if and only if .
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 ,
Proof
Since is the Nim game with pile sizes , the result for Nim shows that the game
is losing for the first player. By Lemma 2, we have
Therefore,
Set . Then , and the algebraic properties of give
Hence,
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 of the SG values of all its successors;
- In particular, the SG value of a terminal state (one with no successors) is .
Nimbers
Every impartial game corresponds uniquely to a nimber. The set of finite nimbers is the set of natural numbers . However, its algebraic properties differ from those of the natural numbers. More specifically, two operations can be defined on nimbers: the Nim sum and the Nim product :
Operations on Nimbers
For nimbers , define:
- Nim sum 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 stones. Two players take turns removing at least and at most stones. The player who removes the last stone wins.
The following result holds:
Theorem
The first player loses if and only if .
Proof 1
When , removing stones leaves the opponent in a losing state. Thus, the current state is winning for the first player.
Conversely, when , there is either no move, or after the first player removes stones, the opponent can immediately remove stones and return the game to a losing state.
Proof 2
As an application of the Sprague–Grundy theorem, let be the SG value of the position with stones remaining.
For , induction gives . This is the same as a single-pile Nim game because the limit on the number of stones removed is not active. For , we can prove that , and hence
These values contain every residue modulo except . Therefore, .
Moore's Nim-k Game
Unlike Nim, Moore's Nim- game allows a move to remove stones from as many as piles at once.
Moore's Nim- Game
There are piles of stones. The -th pile contains stones. Two players take turns removing any positive number of stones from at least and at most 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 , count the number of piles whose size has bit equal to , and take that count modulo . If the remainder is at every bit position, the first player loses; otherwise, the first player wins.
Proof
The proof is analogous to the proof for Nim. Let be the highest binary bit whose remainder is not , and let the corresponding remainder be . The winning strategy is to choose, among the piles whose bit is , piles and remove carefully chosen numbers of stones so that every bit-position remainder in the resulting position is . The only point requiring explanation is why the final choices of removed amounts are always possible.
In fact, after choosing the piles, removing stones from each makes the remainder at bit equal to . 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 piles of stones. The -th pile contains stones. Two players take turns. On each turn, a player either removes any positive number of stones from pile , or moves any positive number of stones from pile to pile . 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, .
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 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 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 is a Fibonacci number.
Proof
Let be the quota, the maximum number of stones that may be removed in the current position. On the first turn, ; thereafter, is twice the number of stones removed on the previous turn. Consider the Fibonacci representation of the remaining number of stones , namely, the unique decomposition of into a sum of positive, nonconsecutive Fibonacci numbers. We prove that the current state is winning if and only if is at least the smallest Fibonacci number in the decomposition of .
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 . It is strictly smaller than the smallest Fibonacci number in the current decomposition. If is the smallest Fibonacci number in the next position, it is also the smallest Fibonacci number in the decomposition of . Write with , that is, are three consecutive Fibonacci numbers. If , adding in Fibonacci representation requires no carry and therefore cannot produce . Thus, . Hence, the next-turn quota 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 and 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 . Then the first player loses if and only if , where is the golden ratio.
The following lemma is needed to prove this result:
Beatty Sequence
Let be irrational. The Beatty sequence it generates is .
Rayleigh's Theorem
Let be irrational numbers satisfying . Then the sequences and form a partition of the positive integers . They are then called complementary Beatty sequences.
Proof
Let . Sort the elements of into a sequence . It suffices to prove that for every ; this gives that is a partition of the positive integers .
First, prove that no element is repeated in the sequence. Otherwise, there would be with . Then
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 not exceeding is exactly . Assume without loss of generality that , so . Counting the elements of and separately, the number of positive integers not exceeding is
Thus, since is strictly increasing, the number of values not exceeding is exactly . Therefore, .
This proves the result stated above.
Proof of the Wythoff Game Result
For every state with that is losing, write it as and let . Then and . Since is the golden ratio, . Rayleigh's theorem shows that the sequences and form a partition of the positive integers . This means that among all losing states with , written , the components and each take every positive integer exactly once, and their difference 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 and assume without loss of generality that , with . If , the first player can remove stones from each pile and reach a losing position. Conversely, by the preceding paragraph, for this value of , there is a unique losing state . If , then clearly ; otherwise, if , choose so that . Since , we have , and therefore . Thus, whenever , we have , and the first player can remove 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 be a well-founded partially ordered set, and let the map satisfy the following conditions: For every , the set is nonempty; for every , we have ; and for every , . At every element of there is a coin, which may be heads-up or tails-up. Players take turns choosing a heads-up coin and a set , then flipping all coins in . 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 and map . The conditions on in the game definition say that whenever a player chooses a set to flip, there is a heads-up coin in such that every element of it precedes . This guarantees that the game terminates after finitely many moves.
Examples
- Let and . This is a row of coins; on each move, a player flips a heads-up coin and may also choose a coin to its left to flip.
- Let and . This is a row of 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.
- Let and . This is an -by- grid of coins; on each move, a player may flip only one heads-up coin.
- Let be the set of vertices of a rooted tree, and let be the family of all subsets containing itself among the subsets of the vertices on the path from vertex 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 , let be the position in which only the coin at element is heads-up. These positions are called basic positions. Every position 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 and a position , let be the set of locations of the heads-up coins. Then the SG value of is
Proof
Consider a related game: in a position , several stones may be placed at each element of . On each move, a player may remove one stone at , choose a set , and place one stone at every element of . For this game, define the basic position as the position with one stone only at . 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 depends only on the parity of the number of stones in each pile, not on their exact counts. Thus, for the position , let the set of positions with an odd number of stones be ; this analysis gives
It remains only to establish the equivalence of and .
For a position of the new game and a position of the coin-turning game, if the locations with an odd number of stones in are exactly the locations of the heads-up coins in , then and are equivalent. By Lemma 2 of the Sprague–Grundy theorem, this is equivalent to proving that is losing. The second player has a simple winning strategy: if the first player removes a stone at and there is more than one stone there, the second player directly imitates the move; otherwise, the second player chooses the same and 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 , and the SG values of successor positions can be obtained inductively:
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 and a vertex . On a turn, when the current position is , the player must choose a vertex adjacent to , call it . The vertex and all its incident edges are then deleted from , leaving a residual graph . The new position is passed to the next player. If, at the start of a turn, the current vertex 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 is an essential vertex of graph 's maximum matching; that is, in every maximum matching of graph , vertex is matched.
Proof
First suppose that vertex is an essential vertex of a maximum matching of . Let have a maximum matching . The first player can move to the vertex in matched with vertex , namely . Since appears in every maximum matching of , the size of a maximum matching of the residual graph is at most . After removing 's edge , we obtain in a matching of size , denoted ; together these two facts show that is a maximum matching of . In the position faced by the second player, vertex is not matched by . Therefore, the second player is in a losing state.
Conversely, suppose there is a maximum matching in which is unmatched. Since is maximum, every vertex adjacent to must be matched; otherwise, adding the edge between them to 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 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 has a perfect matching.
Misère Nim
This section discusses how to solve misère Nim.
Nim Game
There are piles of stones. The -th pile contains 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 is losing if and only if either
- Some satisfies and the Nim sum , or
- For every , we have , and the number of nonempty piles is odd.
Proof
Since having no legal move is a winning state , induction shows that when every pile contains only one stone, an odd number of piles corresponds to a first-player-losing state , while an even number of piles corresponds to a first-player-winning state .
Next, consider positions in which some piles contain strictly more than stone.
Case A: If only one pile contains more than stone, then the Nim sum is necessarily not . Moreover, the first player can move to a position in which every pile contains at most stone and can control the parity of the number of nonempty piles. Thus, this is a first-player-winning state .
Case B: Now suppose more than one pile contains more than stone. Whatever move is made, the next position still has at least one pile containing more than 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:
- 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.
- 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.
- Stop when the queue is empty. Every state not yet classified as winning or losing is drawn.
This algorithm classifies all states in time.
Example Problems
This section discusses several typical example problems.
Luogu P2148 [SDOI2009] E&D
There are piles of stones. For each , piles and 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 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 stones, respectively, and let the SG value be . 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 matrices, with always in the upper-left corner and the other three entries always equal. We may therefore compress the table by replacing each 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 , the value at in the table, denoted by , is given by
The required SG function is . Using this recurrence, the algorithm runs in time to compute .
A simple induction also shows that is the minimum number of times one must repeatedly divide and by simultaneously to obtain two even numbers. Equivalently, form the bitwise OR of and ; the number of its trailing bits equal to 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 be the set of SG values of the positions obtained by splitting stones into two nonempty piles. Then , so satisfies the recurrence
We need to prove that if and only if the binary representation of has bit (the lowest bit is bit ) equal to .
Use mathematical induction. The base case is immediate. Assume the statement holds for every positive integer smaller than . Then if and only if there exist such that , at least one of the bits of and at positions is , and both bit values are . Clearly, such a split exists if and only if, considering only bits , namely modulo , the value of lies in the interval . This condition is equivalent to having bit equal to . 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 piles of stones, and the -th pile contains 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 .
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 , and the Nim sum of all designated piles is . Then the first player cannot win if and only if ; in other words, the number of stones in pile , namely , does not exceed the Nim sum of all piles except pile , namely . Since the data range is small, enumerate directly the pile designated for the first-turn move. When enumerating pile , 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 .
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 piles of stones, and the -th pile contains 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 , this is Nim. When , the problem becomes more complicated. However, because only the two end piles can be operated on, let their numbers of stones be and , respectively. Further, let be the indicator of a first-player-winning state: when the first player wins and otherwise. It is easy to see that satisfies the recurrence if and only if, for every and , we have . When or , the game has fewer than piles and the numbers of the middle piles must be considered further. Therefore, temporarily assume that and are known, and consider how to derive all values of from them. This is not difficult. Consider an infinite matrix whose index set is . Computing amounts to filling it with and , under the conditions that each row and column contains at most one , and that if no earlier position in the same row or column has been , the position is . The positions of the s in each row define a function from row number to column number . After trying a few examples (that is, making a table), one finds that if the unique value satisfying is the value , and the unique value satisfying is the value , then, for every , the condition holds when
Thus, once and are known, any position can be computed in time, determining and whether the current state is winning for the first player. The values and can be computed recursively. For example, is the unique solution of , while the value of can be computed by removing the rightmost pile and considering only the remaining piles; that is, considering only the first piles, one can likewise compute , and evidently . Similarly, after removing the leftmost pile and computing , we obtain . Of course, computing the inner functions and depends on functions for still smaller intervals. This is a typical interval DP. Each layer only needs to maintain the corresponding and 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:
- Luogu P2197 Template Nim Game
- Luogu P2252 [SHOI2002] Stone-Taking Game
- Luogu P2594 [ZJOI2009] Coloring Game
- Luogu P3185 [HNOI2007] Splitting Game
- Luogu P3480 [POI 2009] KAM-Pebbles
- Luogu P4101 [HEOI2014] Everyone Says Jiangnan Is Beautiful
- Luogu P4279 [SHOI2008] Little John's Game
- Luogu P6487 [COCI 2010/2011 #4] HRPA
- Luogu P6560 [SBCOI2020] The Passage of Time
- Luogu P7589 Black-and-White Chess (2021 CoE-II B)
- AtCoder Regular Contest 168 B - Arbitrary Nim
Then come some problems requiring stronger insight or more comprehensive techniques:
- Luogu P2490 [SDOI2011] Black-and-White Chess
- Luogu P3179 [HAOI2015] Array Game
- Luogu P5363 [SDOI2019] Moving Gold
- Luogu P5970 [POI 2016] Nim z utrudnieniem
- Luogu P6791 [SNOI2020] Stone-Taking Game
- Luogu P7864 EVOI-RD1 Picking Leaves
- Luogu P8347 Wdoi-6: The Other Side of the Moon
- AtCoder Grand Contest 002 E - Candy Piles
- AtCoder Grand Contest 010 F - Tree Game
- AtCoder Grand Contest 017 D - Game on Tree
- AtCoder Beginner Contest 278 G - Generalized Subtraction Game
- SPOJ COT3 - Combat on a tree
- Codeforces 494 E. Sharti
- Codeforces 1149 E. Election Promises
- Codeforces 1451 F. Nullify The Matrix
- Codeforces 1704 F. Colouring Game
Finally, some bipartite graph game problems are listed separately because they require algorithms for bipartite graph matching:
- Luogu P4136 Who Can Win?
- Luogu P4617 [COCI 2017/2018 #5] Planinarenje
- Luogu P4055 [JSOI2009] Game
- Luogu P1971 [NOI2011] Rabbit and Egg Game
- Codeforces 1147 F. Zigzag Game
References and Notes
- (Reposted) Nim Game Strategy (Complete Collection) by exponent - cnblogs
- [Combinatorial Games and Game Theory] [Study Notes] by Candy? - cnblogs
- Nim - Wikipedia
- Sprague–Grundy theorem - Wikipedia
- Nimber - Wikipedia
- Beatty Sequence - Wikipedia
- Games on arbitrary graphs - CP Algorithms
- Algorithm Study Notes (74): Bipartite Graph Games by Pecco - Zhihu
- Conway, John H. On numbers and games. AK Peters/CRC Press, 2000.
- Berlekamp, Elwyn R., John H. Conway, and Richard K. Guy. Winning ways for your mathematical plays, volume 1-4. AK Peters/CRC Press, 2001-2004.
Footnotes
-
The names “ state” and “ state” respectively mean “Next player wins” and “Previous player wins”. ↩
-
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. ↩