๐ณ From coin-sliding parity to tree pursuit and permutation state machines
Welcome, future tree game strategist! ๐ This article dives into games played on trees and permutations โ from fixed-move coin-sliding parity to tag-style pursuit on tree graphs and state-transition games on permutations. These problems blend graph theory, parity arguments, and game-tree analysis, and appear in Codeforces, AtCoder, and competitive programming rounds worldwide.
Trees are the simplest non-trivial graphs โ they have no cycles, which means many problems that are NP-hard on general graphs become solvable on trees. Game theory on trees is particularly rich because:
Unique paths: Between any two nodes, there's exactly one path โ distance is well-defined and easy to compute.
Leaves are special: The leaves (degree-1 nodes) are natural "endpoints" that get removed in many games.
Centroid decomposition: Trees have centroids โ nodes whose removal splits the tree into balanced subtrees.
Parity arguments: Many tree games reduce to counting nodes modulo 2, or comparing distances.
Permutations as graphs: Permutation games often reduce to analyzing cycles and inversions.
In this article, we'll cover three classic problem families: coin-sliding games on trees, pursuit-evasion (tag) on trees, and state-transition games on permutations. Each reveals a different flavor of strategic thinking.
1. Game on Leaves โ Coin Sliding on a Rooted Tree
Practice problem rules: A rooted tree has coins at specified nodes. On each turn, move exactly one coin exactly one edge toward its parent. A coin reaching the root is removed. Whoever makes the last move wins. Coins do not block one another.
Note
Do not confuse two different games. Deleting leaves from a tree, deleting a specially marked vertex, and sliding coins toward the root have different legal moves and different winning conditions. The linked Game on Leaves exercise below is the coin-sliding variant.
Invariant: the number of moves cannot change
A coin at depth d must travel exactly d parent edges before reaching the root. The players can choose which coin to move, but cannot change any path length. Therefore, the total number of turns is the sum of the initial coin depths. Odd turns mean the first player wins; even turns mean the second player wins. This is a fixed-move parity game, not a Nim-sum/XOR-of-depths game.
Each coin contributes a fixed number of parent-edge moves equal to its starting depth. The first player wins exactly when the total move count is odd.
example.js
function gameOnLeaves(n, edges, tokens) {
const adj = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
adj[u].push(v);
adj[v].push(u);
}
const parity = new Uint8Array(n);
const visited = new Uint8Array(n);
visited[0] = 1;
const queue = [0];
for (let i = 0; i < queue.length; i++) {
const u = queue[i];
for (const v of adj[u]) {
if (visited[v]) continue;
visited[v] = 1;
parity[v] = parity[u] ^ 1;
queue.push(v);
}
}
let movesParity = 0;
for (const u of tokens) movesParity ^= parity[u];
return movesParity ? "First" : "Second";
}
// Single coin at depth 2 => exactly 2 moves => Second wins.
// Two depth-1 coins => exactly 2 moves => Second wins.
Key Insight
Count moves, not vertices or leaves. Tree shape affects each node's depth but does not give players control over the total number of parent-edge traversals.
Problem: Alice and Bob are on a tree. Alice moves first. Each turn, Alice can move up to da edges, Bob can move up to db edges. Alice wants to catch Bob (occupy the same node). Bob wants to evade forever. Who wins?
Note
๐ Real-World Analogy: Imagine a game of tag on a branching network of bridges. Alice runs faster (more edges per turn) but Bob knows the terrain. The question: given the network structure and both speeds, can Alice always corner Bob? If Alice is fast enough, the tree's diameter limits how far Bob can run.
The Distance Model
Tree tag is fundamentally a distance game. Since there's only one path between any two nodes, the game reduces to tracking the distance between Alice and Bob over time.
Tree Tag: positions and distances on a tree. Alice's capture range, Bob's mobility, and the tree diameter determine who can force the outcome.
Analysis
Let dist(a, b) be the initial distance between Alice and Bob. The game has three key parameters:
da โ Alice's speed (max edges per turn)
db โ Bob's speed (max edges per turn)
D โ the tree's diameter (longest shortest path)
Winning Conditions
example.js
function treeTagWinner(n, edges, a, b, da, db) {
// n = nodes, a = Alice's start, b = Bob's start
// da = Alice's speed, db = Bob's speed
// Returns "Alice" or "Bob"
// Build adjacency
const adj = Array.from({ length: n + 1 }, () => []);
for (const [u, v] of edges) {
adj[u].push(v);
adj[v].push(u);
}
// BFS to find distances from Alice
function bfs(start) {
const dist = Array(n + 1).fill(-1);
const q = [start];
dist[start] = 0;
for (const u of q) {
for (const v of adj[u]) {
if (dist[v] === -1) {
dist[v] = dist[u] + 1;
q.push(v);
}
}
}
return dist;
}
const distFromA = bfs(a);
const initialDist = distFromA[b];
// 1. Alice catches Bob on first move
if (da >= initialDist) return "Alice";
// 2. Bob's speed doesn't matter if Alice is slow enough
// Bob can run to the farthest leaf and stay there
const distFromB = bfs(b);
// Find the farthest node from Bob (diameter end)
let farNode = 1;
for (let i = 2; i <= n; i++) {
if (distFromB[i] > distFromB[farNode]) farNode = i;
}
// Distance from that far node to Alice
const distFromFar = bfs(farNode);
const diameter = Math.max(...distFromFar.slice(1));
// 3. If Alice can reach any node within 2*da, she wins
// because she can shrink Bob's safe zone every turn
if (2 * da >= diameter) return "Alice";
// 4. If Bob is strictly faster than Alice, he can always evade
if (db > 2 * da) return "Bob";
// 5. Otherwise, compare: if Alice can catch Bob in a game of tag
// on the tree's diameter path, she wins
// Core insight: Bob's effective speed is min(db, diameter)
return da > db ? "Alice" : "Bob";
}
๐ Real-Time Thinking
"Let me think about this step by step. Alice moves first. Can she catch Bob immediately? Check da >= dist(a, b). If yes, game over โ Alice wins on turn 1.
"If not, Bob runs. Bob's strategy is to always move to the farthest node from Alice. On a tree, the maximum distance is bounded by the diameter. If 2 * da >= diameter, Alice can reach any node from any other node in two moves โ meaning she can always shrink the distance.
"If db > 2 * da, Bob can outrun Alice โ every time Alice gets close, Bob dashes to the opposite side of the tree. He's simply too fast.
"Otherwise, it's a pure speed comparison. Alice's speed advantage determines the outcome. If da > db, Alice eventually corners Bob. If not, Bob can evade by always moving away."
Platform rules: A permutation contains each integer from 1 through n. On a turn the player must choose the leftmost remaining value x. If x is the maximum remaining value, the player wins immediately. Otherwise, delete every value greater than x, leave the leftmost position in place, and pass the turn to the opponent.
Key Insight
Key invariant: After any nonwinning first move, the original leftmost element stays in place while all larger values disappear. The second player then sees a leftmost element that is the maximum and wins immediately. There is no choice of end positions, and neither LIS parity nor inversion parity determines this variant.
Permutation Game โ Forced Leftmost Selection. Only the leftmost remaining position is selectable each turn. Alice wins iff the initial leftmost element equals n.
Optimal outcome in constant time
example.js
function permutationGameCF(perm) {
const n = perm.length; // permutation of 1..n
return perm[0] === n; // true exactly when Alice wins
}
// [3,1,2] -> true; Alice chooses maximum 3 immediately.
// [2,3,5,1,4] -> false; Bob sees [2,1] after Alice's move.
// [1,2,3,4] -> false; Bob sees [1].
// Time O(1), space O(1).
Note
This is not the classic pick either end to maximize scoreproblem, which uses interval DP. It is also not theremove increasing subsequences problem. Always distinguish the permitted actions before choosing a strategy.
Beyond coin-sliding and tree-tag problems, trees host a rich variety of strategy games. Let's explore two more problems that appear frequently in competitive programming.
๐ง Let's Go Hiking
Problem: Alice and Bob go hiking on a mountain represented by an array of heights. Alice starts at position p. On each turn, Alice moves left to a lower position, Bob moves right to a lower position. The player who cannot move loses.
This is a tree game in disguise! The "mountain" array can be modeled as a tree where edges go from higher to lower adjacent positions. Each player has their own "movement tree" โ Alice's moves go left, Bob's go right.
Key Insight
๐ Key Insight: Since Alice can only move left and Bob only right, their games are independent! The winner is determined by comparing the length of the longest decreasing path each player can take. If Alice's longest path is strictly longer than Bob's, Alice wins. If Bob's is longer, Bob wins. If equal, Bob wins (Alice moves first, so she exhausts her moves first and Bob gets the extra turn).
example.js
function letsGoHiking(arr, p) {
// arr = mountain heights, p = Alice's start (0-indexed)
const n = arr.length;
// Alice can only move left to lower positions
let aliceMoves = 0;
let pos = p;
while (pos > 0 && arr[pos - 1] < arr[pos]) {
aliceMoves++;
pos--;
}
// Bob can only move right to lower positions
let bobMoves = 0;
pos = p;
while (pos < n - 1 && arr[pos + 1] < arr[pos]) {
bobMoves++;
pos++;
}
// Alice needs strictly more moves to win
if (aliceMoves > bobMoves) return "Alice";
return "Bob";
}
๐ช Deforestation โ The Game of Removing Subtrees
Problem: Given a rooted tree, players alternately remove a subtree (any node and all its descendants). The player who removes the root wins. This is a classic impartial combinatorial game on trees.
The solution uses Grundy numbers (also known as Nimbers) on trees. Each node's Grundy number is the XOR of (grundy[child] + 1) for all children.
example.js
// Deforestation โ Grundy Number Solution
// Grundy(node) = XOR over children of (grundy(child) + 1)
function deforestationGrundy(adj, root, parent = -1) {
let xor = 0;
for (const child of adj[root]) {
if (child === parent) continue;
const childGrundy = deforestationGrundy(adj, child, root);
xor ^= (childGrundy + 1);
}
return xor;
}
// If Grundy(root) !== 0, first player wins
// If Grundy(root) === 0, second player wins (P-position)
Tip
โก Pro Tip: The "+1" in (grundy(child) + 1)accounts for the fact that when you remove a node, you can also choose to remove any subset of its children's trees. This formula is the standard "tree Nim" reduction and appears in many Tree DP + game theory problems.
Q1: How do I know if a tree game reduces to parity? If the game is impartial (same moves for both players) and the only relevant property is "can I make the last move?", count the total number of moves modulo 2. Key trick: if the target node is a leaf, first player wins immediately.
Key Insight
Q2: What's the most important metric in tree pursuit games? The diameter and the initial distance. If 2 * Alice's speed โฅ diameter, Alice can reach any node in 2 turns โ she wins regardless of Bob's speed. If Alice's speed > Bob's speed, she eventually corners him.
Key Insight
Q3: When should I use DP vs Grundy numbers on trees? Use interval DP when players remove from ends (left/right). Use Grundy numbers when players remove arbitrary nodes or subtrees โ the XOR of (grundy[child] + 1) formula handles all impartial tree games.
Key Insight
Q4: How do permutation games differ from array games? Permutations have distinct elements (1..n each exactly once), which means you can reason about inversion count, LIS length, and fixed points. Arrays can have duplicates, which changes the analysis completely.
Key Insight
Q5: What's the "Let's Go Hiking" pattern? Two players, two directions, independent movement. Compare the longest monotonic decreasing path in each direction from the starting point. Whoever has strictly more moves wins. If equal, second player wins (first player exhausts first).
๐ Key Takeaways
Tree games reduce to path analysis โ unique paths between nodes make distance and parity easy to compute
Coin sliding has fixed move count โ sum each coinโs starting depth; odd total means the first player wins
Tree tag winner depends on diameter vs. speed โ 2 * da โฅ D means Alice always wins
Bob wins if db > 2*da โ strictly faster Bob can outrun Alice on any tree
Permutation games from ends โ interval DP โ dp[l][r] = max(perm[l] - dp[l+1][r], perm[r] - dp[l][r-1])
Permutation games (any removal) โ sorted prefix length parity โ unsorted segment parity determines the winner
"Hiking" style โ compare longest monotonic paths โ strictly longer path wins; tie favors second player
Time: O(n) or O(nยฒ) โ tree games are generally polynomial; DP variants are O(nยฒ) for interval DP
Practice! โ The only way these patterns become instinctive is by solving. The Playground is your dojo ๐ฅ
Note
๐ฎ What's Next? Now that you've mastered tree and permutation games, head over to Advanced Game Strategiesfor Wythoff's Game, Flip Game, and more complex combinatorial puzzles!