Four problems rated 2,200 to 2,400 about who wins a game played perfectly. The move: give each position a value, so that independent games add by xor, and count the moves that reach value 0.
Each problem in this tent is a game for two players who play perfectly. A player who cannot move loses. The question is who wins, or how many first moves leave the other player in a lost position.
The table names the game and the number that decides it.
| Problem | The game | What decides the winner |
|---|---|---|
| A race down the pipeline | move jobs one stage closer to release | the xor of the odd stages |
| Closing street segments, one or two at a time | close one or two neighbouring segments | the xor of the values of the streets |
| Following related topics until someone is stuck | move a token along a link | outcomes spread back from the topics with no link out |
| Whoever clears the last result loses | take results, and taking the last loses | the Nim xor, except when every list has at most one result |
A game with a very large tree of moves can have a tiny summary. Trying all the moves does not scale, so each position gets a number.
Here is how the number is built, on a game with one pile. A move takes 1, 3 or 4 items. The value of a pile is the smallest whole number that is not the value of any pile one move away.
Exercise · Predict the output: The values of a pile. A move takes 1, 3 or 4 items from a pile. The value g of a pile of n items is the smallest number that is not the value of a pile one move away. A pile of 0 has value 0. What does the code print for the piles of 0 to 9 items?
moves = [1, 3, 4]
g = []
for n in range(10):
seen = {g[n - m] for m in moves if n - m >= 0}
v = 0
while v in seen:
v += 1
g.append(v)
print(" ".join(map(str, g)))The move has two parts.
First, label positions from the ends. A position with no move is lost for the player to move. A position is won if some move leads to a lost position, and lost if every move leads to a won one.
Second, for games that are sums of independent parts, give each part a value, as in the prediction above. The value is the smallest number missing from the values one move away, called the mex. The value of the whole game is the xor of the values of the parts.
The value of a position is the mex of the values of the positions one move away. For independent games the value of the sum is the xor of the parts, and the player to move loses exactly when it is 0.
A winning first move is a move that reaches value 0. In ordinary Nim a pile is its own value. With the xor total of all piles, a pile a must go down to a xor total, which is possible only if that is smaller than a.
For the piles 3, 4 and 5, the total is 2. Only the pile 3 can go to 3 xor 2, which is 1, so there is exactly 1 winning move.
Give each pile a value, xor the piles, and a winning move reaches a total of zero. Piles 3, 4 and 5 have one such move.
The rule "smaller than a" is easy to weaken by one character.
Exercise · Find the bug: The move that changes nothing. This counts the first moves in ordinary Nim that leave the other player in a lost position. It counts one move for each pile that can reach the target size. It overcounts on some boards. Which line is wrong?
def count_winning_moves(piles):
total = 0
for a in piles:
total ^= a
count = 0
for a in piles:
if (a ^ total) <= a:
count += 1
return countThe Academy lessons Bits and maths basics, Graph traversal and DP from recursion gave you xor, graph walks and tables. This tent changes four things.
The pile is hidden. In the pipeline problem jobs move one stage closer, and the moves of the even stages can be undone by the other player. Only the odd stages behave as the piles of Nim.
A move can split a game. Closing segments cuts a street into two streets, so the value of a street is the mex over all splits of the xor of the two parts. The values for streets of 0 to 11 segments are 0, 1, 2, 3, 1, 4, 3, 2, 1, 4, 2 and 6. A table for 1,000 segments takes 1,000,000 steps.
The positions form a graph. Solve it backwards from the positions with no move, which are lost. For 50,000 topics and 100,000 links that is about 150,000 steps. A position that never gets decided is a draw: two topics that link to each other draw.
The last move can lose. In the misere game the Nim rule holds until every list has at most one result. Then the player to move wins when the number of single results is even.
Three single results: the players alternate and the first takes the last one. The ordinary rule says the first wins.
Applying the ordinary rule to the misere game fails on the smallest boards.
Exercise · Break it: The last result loses. This says whether the first player wins a game of lists where removing the very last result loses. It applies the ordinary Nim rule. Find an input where it is wrong.
def first_wins(piles):
total = 0
for a in piles:
total ^= a
return total != 0The limits tell you whether the game has a closed form.
| Limit | What it tells you |
|---|---|
| piles up to 10^9, 100,000 piles | no table by pile size: a rule on the xor, in one pass |
| streets up to 1,000 segments | a table of values up to 1,000: about 10^6 steps |
| 50,000 topics, 100,000 links | O(n + m) backwards from the lost positions |
| draws are possible | a third answer: positions never decided |
| values and totals | the xor of 10^9 values fits in a 32-bit integer |
The full treatment is in Fast I/O and stress testing. The first line holds the number of piles n, and the second holds the piles. The program prints first when the xor is not 0, and second when it is.
It was run on the sample of the piles 3 4 5, which prints first. On 100,000 piles of 1,000,000,000 it prints second, because an even number of equal piles cancels.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
total = 0
for i in range(n):
total ^= int(data[1 + i])
sys.stdout.write("first\n" if total != 0 else "second\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine().trim());
StringTokenizer st = new StringTokenizer(in.readLine());
int total = 0;
for (int i = 0; i < n; i++) total ^= Integer.parseInt(st.nextToken());
System.out.println(total != 0 ? "first" : "second");
}
}#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int total = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
total ^= x;
}
cout << (total != 0 ? "first" : "second") << "\n";
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
let total = 0;
for (let i = 1; i <= n; i++) total ^= data[i];
process.stdout.write(total !== 0 ? "first\n" : "second\n");The brute force tries every move of every position. It is slow, and easy to check by eye. Run it against the fast rule on small boards, and stop at the first difference.
import random
from fast import count_winning_moves
from slow import count_winning_moves as slow_count
for seed in range(1000):
rng = random.Random(seed)
piles = [rng.randint(0, 4) for _ in range(rng.randint(1, 4))]
if count_winning_moves(piles) != slow_count(piles):
print("different at seed", seed, piles)
break
else:
print("all 1000 inputs agree")On the misere solution it printed all 1000 inputs agree. With the ordinary Nim rule in place of the misere rule, it stops at seed 22 on the piles 1 and 0.
Problems rated 2,200 to 2,400 hide a standard game inside a story, and then bend it. Spend the first ten minutes on the hidden game: name the piles, the moves and who loses. The stress test finds a bent rule that you forgot.
The ratings go 2,200, 2,300, 2,300 and 2,400. The first hides Nim in a staircase. The second needs a table of values for streets that split. The third is a game on a graph, with draws, and the last is Nim with a twist.
For each problem, write three lines before you code: the hidden game, what a position is, and what a winning move must reach. If the positions form a graph, write which positions are lost first.
Checkpoint · Games and Sprague-Grundy
Q1/5 A move takes 1, 3 or 4 items from a pile. What is the value of a pile of 4 items?
Answer: C
The value is the smallest number missing from the values one move away. A pile of 4 reaches piles of 3, 1 and 0, with the values 1, 1 and 0, so 0 and 1 are present and the value is 2.
Q2/5 The piles of an ordinary Nim game are 3, 4 and 5. How many winning first moves are there?
Answer: B
The xor is 2. A pile a can go to a xor 2 only if that is smaller than a. For 3 it is 1, which is smaller. For 4 and 5 it is 6 and 7, which are larger.
Q3/5 In ordinary Nim the piles are 3 and 3. Why is the number of winning first moves 0?
Answer: B
A position with xor 0 has value 0 and is lost for the player to move. A comparison of at most instead of smaller than would count 2 moves that take nothing.
Q4/5 On a graph game, two topics link to each other and nothing else. Who wins from the first topic?
Answer: C
Each topic has a move, and no move reaches a lost topic. The outcome never gets decided, so it is a draw.
Q5/5 In the game where removing the very last result loses, the lists are 1, 1 and 1. Who wins, and what does the ordinary Nim rule say?
Answer: C
The players must alternate on single results, so the first player takes the last one and loses. The ordinary rule sees the xor 1 and predicts a win.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.