DSA · Competitive Programmer · Pattern 8 of 9
Game Theory
9 problems.
Your progress0%
- 1st Visit
- 0/9
- 2nd Visit
- 0/9
- Revise
- 0/9
About this pattern
In an impartial game both players have the same moves, and under normal play the player who cannot move loses. Classify positions backwards: a position is winning if some move reaches a losing position, and losing if every move reaches a winning one. Brute-forcing small cases often reveals a periodic pattern that can be proved afterwards. When a game splits into independent parts, the Sprague-Grundy theorem assigns each part a Grundy number, the minimum excluded value among its options, and the whole position is losing exactly when the XOR of those numbers is zero. Score-based games instead use minimax DP on the difference between the two players' totals.
// Grundy numbers of one pile when a move removes any amount listed in moves
vector<int> grundy(int maxN, const vector<int>& moves) {
vector<int> g(maxN + 1, 0);
for (int n = 1; n <= maxN; n++) {
vector<bool> seen(moves.size() + 2, false);
for (int m : moves)
if (m <= n && g[n - m] < (int)seen.size()) seen[g[n - m]] = true;
while (seen[g[n]]) g[n]++; // mex of the reachable values
}
return g;
}
// A sum of independent piles is losing iff the XOR of g[pile] is 0
Problems
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | Stone Game III | LeetCode | Hard | Solve Stone Game III on LeetCode (opens in a new tab) | |||
| 2 | 1-2-K Game | Codeforces | Medium 1700 | Solve 1-2-K Game on Codeforces (opens in a new tab) | |||
| 3 | Stoned Game | Codeforces | Hard 1800 | Solve Stoned Game on Codeforces (opens in a new tab) | |||
| 4 | A Lot of Games | Codeforces | Hard 1900 | Solve A Lot of Games on Codeforces (opens in a new tab) | |||
| 5 | GameGame | Codeforces | Hard 1900 | Solve GameGame on Codeforces (opens in a new tab) | |||
| 6 | Tree Tag | Codeforces | Hard 1900 | Solve Tree Tag on Codeforces (opens in a new tab) | |||
| 7 | Cat and Mouse | LeetCode | Hard | Solve Cat and Mouse on LeetCode (opens in a new tab) | |||
| 8 | Not a Nim Problem | Codeforces | Hard 2100 | Solve Not a Nim Problem on Codeforces (opens in a new tab) | |||
| 9 | Lieges of Legendre | Codeforces | Hard 2200 | Solve Lieges of Legendre on Codeforces (opens in a new tab) |