Before introducing the SG function and SG theorem, let's introduce the must-win and must-defeat points.
Now let's introduce today's protagonist. The sums of combinatorial games are often complex, but there is a new tool that makes combinatorial problems simple - the SG function and the SG theorem.
Sprague-Grundy Theorem (SG Theorem):
The SG function of the game sum is equal to the Nim sum of the respective game SG functions. This makes it possible to divide and conquer each subgame, simplifying the problem. The Bouton's theorem is a direct application of the Sprague-Grundy theorem in Nim games, because the SG function of a single stack of Nim games satisfies SG(x) = x. If you don't know the Nim game, please move: here
SG function:
First define the mex (minimal excludant) operation, which is an operation applied to a set, representing the smallest non-negative integer that does not belong to the set. For example mex{0,1,2,4}=3, mex{2,3,5}=0, mex{}=0.
For any state x, define SG(x) = mex(S), where S is the set of SG function values for the successor states of x. If x has three successor states SG(a), SG(b), SG(c), then SG(x) = mex{SG(a), SG(b), SG(c)}. In this way, the final state of the set S must be an empty set, so the final state of the SG function is SG(x) = 0, if and only if x is the inevitable point P.
[Example] The problem of taking stones
There is a pile of n stones, and only { 1, 3, 4 } stones can be taken at a time. The one who takes the stones first wins. What is the SG value of each number?
SG[0]=0,f[]={1,3,4},
When x=1, 1 - f{1} stones can be removed, leaving {0} stones, so SG[1] = mex{ SG[0] }= mex{0} = 1;
When x=2, 2 - f{1} stones can be removed, leaving {1} stones, so SG[2] = mex{ SG[1] }= mex{1} = 0;
When x=3, 3 - f{1,3} stones can be removed, leaving {2,0} stones, so SG[3] = mex{SG[2],SG[0]} = mex{0, 0} = 1;
When x=4, 4- f{1,3,4} stones can be removed, leaving {3,1,0} stones, so SG[4] = mex{SG[3],SG[1],SG [0]} = mex{1,1,0} = 2;
When x=5, 5 - f{1,3,4} stones can be removed, leaving {4,2,1} stones, so SG[5] = mex{SG[4],SG[2],SG [1]} =mex{2,0,1} = 3;
And so on...
x 0 1 2 3 4 5 6 7 8....
SG[x] 0 1 0 1 2 3 2 0 1....
From the above example, we can get the steps to solve the SG function value, then the steps to calculate the SG function value of 1~n are as follows:
1. Use the array f to record the ways in which the current state can be changed.
2. Then we use another array to label the successor states of the current state x.
3. Finally, simulate the mex operation, that is, we search for the minimum value of the unmarked value in the marked value and assign it to SG(x).
4. We keep repeating the steps 2 - 3 to complete the calculation of the function value of 1~n.