Some problems hide no clever idea at all. The statement describes a process — a card game, a printer, a railway yard — and asks what happens in the end. To solve one, make the program do exactly what the statement says, step by step, in the same order. That is a simulation.
The thinking goes into two questions: how to keep the state of the process, and how not to get a single detail wrong. Stacks, queues and deques answer the first question surprisingly often.
Choose the container from the story
The wording of a statement usually names the container for you:
| The statement says… | Keep it in |
|---|---|
| "in the order they arrived", "a line", "takes turns", "goes to the back" | queue |
| "on top", "the most recent", "the last one placed", "undo" | stack |
| "at either end", "the leftmost or the rightmost" | deque |
| "the k-th one", "any position" | vector |
A card game: two decks, two queues
Two players each hold a deck; all the cards are different. In every fight both turn over their top card; the higher card wins, and its owner puts first the beaten card, then their own at the bottom of their deck. Whoever runs out of cards loses. Print the number of fights and the winner,
1or2— or-1if the game never ends.
Input
Output
Top cards come from the front, won cards go to the back: each deck is a queue.