If you had asked 10-year-old me what I thought about Alice and Bob, frustration would definitely not be among my top thoughts. I mean, Alice in Wonderland and Bob the Builder were pretty cool! 🤩
And yet now, every time they put a Div. 2 C problem featuring Alice and Bob, I just internally dread a little 😨. But after much practice, I've come to realize that most of the time, these questions are actually quite fun to score on.
Usually, the solution code is surprisingly concise or simple, often requiring no complex external data structures 😮. That is exactly what I wish to demonstrate in this blog post: questions based on games in Competitive Programming are not necessarily evil.
What is a "Game" Problem in CP?
Aside from our favorite individuals Alice and Bob appearing, games questions usually involve a two-player perspective where each player takes turns making certain "moves". The player who cannot make a valid move on their turn loses (normal play convention).
In other variations, players work towards opposite objectives—for example, one player tries to minimize a certain value while the other attempts to maximize it.
These moves typically consist of operations on arrays, strings, or single integers under strict rules. Below are four common strategies and paradigms you can use to approach these problem statements.
1. Simulation
Often, the game involves a small, bounded number of total moves. For instance, if an element is deleted from an array of size at every turn, at most moves can occur.
Let:
- = Maximum possible number of moves in the game.
- = Operations required to compute/select an individual optimal move.
If the sum of over all test cases is well under (for a standard 1-second time limit), we can simply simulate the game directly—making the most optimal choice for the active player at each turn.
Example Scenario:
Alice and Bob have an array of integers (, ). On each turn, a player picks one integer, adds it to their total score, and removes it from the array. Both players want to maximize their score, and Alice goes first. Determine final scores.
Since one element is removed each turn, there are at most turns. To maximize their score greedily, each player should always choose the largest available element. While finding the maximum in an unsorted array takes time, we can preprocess by sorting the array in time and popping elements from the end:
- 1st largest Alice
- 2nd largest Bob
- 3rd largest Alice ... and so on.
2. Quick Games
Sometimes games end in just 1 or 2 moves. Or perhaps Alice has no valid moves right at the start, leading to an immediate win for Bob!
Identifying such patterns requires dry-running small test cases on paper. If you notice that no game ever progresses past 1 or 2 turns regardless of input size, you're dealing with a Quick Game.
General resolution flow:
- Check if Alice has a valid move at . If no Bob wins.
- Check if Alice can make a move that leaves Bob with zero valid moves at . If yes Alice wins, else Bob wins.
Example Problem: Sorting Games
Alice and Bob play on a binary string of length . On a player's turn, if is not sorted, they choose a non-increasing subsequence of indices (where ) and reverse it. The first player unable to move loses.
Problem reference: CF 2190 A - Sorting Games
Let's test some cases:
- : Already sorted. Alice has no moves. Bob wins.
- : Alice selects indices (). Reversing yields . is now sorted, Bob has no moves. Alice wins.
- : Alice selects indices (). Reversing yields . Sorted! Alice wins.
Notice the pattern: if the string is initially unsorted, Alice can always sort the entire string in a single move!
How to construct Alice's move?
Let be the total count of 0s in . In a sorted string, the first characters must all be 0s.
If the current first characters contain ones, then there must also be exactly zeros in the remaining characters. By selecting those ones and zeros as her non-increasing subsequence and reversing them, the string becomes completely sorted in 1 turn! Fuiyohh! 💡
3. Winning and Losing States
In finite combinatorial games:
- A Losing State is one from which every valid move leads to a Winning State for the opponent.
- A Winning State is one from which at least one valid move exists that hands the opponent a Losing State.
The game reduces to identifying whether the initial state is a Winning or Losing state for Alice.
Example Scenario:
Alice and Bob are in an -floor building (floors to ). The elevator can move at most floors down per turn (). Starting at floor , players alternate moving down. The player who lands on floor wins. ().
- Floor : Losing State (game already ended/lost for active player).
- Floors to : Winning States (active player can move directly to floor ).
- Floor : Losing State (any valid move lands on a floor in , handing the opponent a winning state!).
- Floors to : Winning States (active player can force opponent to floor ).
Pattern recognition shows that any floor where is a Losing State. Thus, if , Bob wins; otherwise, Alice wins!
4. Response Moves
In some games, one player (say, Bob) can only win by precisely mirroring or responding to every single move made by Alice.
Example Problem: Removals Game
Alice and Bob each have a permutation of integers . In each turn of rounds, Alice deletes an element from either end of her permutation, then Bob deletes an element from either end of his permutation. At the end, 1 element remains in each sequence. If both remaining elements are identical, Bob wins; otherwise Alice wins.
Problem reference: CF 2002 B - Removals Game
Simulating this yields possibilities—far too slow for .
Instead, observe Bob's winning condition: Bob must ensure that at every step, the set of remaining elements in both permutations remains identical. If Alice ever deletes an element that Bob cannot match from his endpoints, Alice can isolate that difference and win.
For Bob to successfully mirror Alice's moves from the very first turn, the endpoints of their permutations must match.
- Case 1: and . If Alice deletes , Bob deletes . The game recursively reduces to matching sub-arrays, requiring overall.
- Case 2: and . If Alice deletes , Bob deletes . The game recursively requires .
Thus, Bob wins if and only if or . Otherwise, Alice wins.
Practice Problems
Here is a curated collection of Codeforces game problems to test your understanding, ranging from entry-level to advanced:
- CF 959 A - Mahmoud and Ehab and the even-odd game : Solution Link
- CF 1373 B - 01 GameSolution Link
- CF 1842 A - Tenzing and Tsondu
- CF 2055 A - Two Frogs : Solution Link
- CF 2060 C - Game of Mathletes
- CF 1931 E - Anna and the Valentine's Day Gift
- CF 2002 B - Removals Game
- CF 2123 D - Binary String Battle
- CF 2190 A - Sorting Games
- CF 2006 A - Iris and Game on the Tree
- CF 2171 C2 - Renako Amaori and XOR Game (hard version)
- CF 2236 D - Brand New Tatar TV Show
- CF 2245 E - Tom and Jerry
With that, I conclude this post! I hope this guide helps you overcome your fear of Alice and Bob on Codeforces. 🥳 If you have any questions or thoughts, feel free to drop a comment below!