Card Shuffle (Large)
InterviewTime limit5sMemory limit512 MB
Find the card at position W after moving the given blocks of a numbered M-card deck to the top C times.
- Level
Medium5 of 10
- Topics
- Simulation, Intervals
- Solved
- No attempts yet
Problem
Frank likes card games and spends his weekends at game parties in a friend's house. The deck they play with has cards, each carrying a different number from to . Frank owns the same automatic shuffling machine his friend uses at those parties, and he knows how it works. The machine shuffles the deck by cutting the pile times. Cut takes cards starting at the -th card from the top, that is the cards at positions through , and moves them to the top of the pile without changing their order.
One day the usual deck got dirty, so they opened a new one. The new deck went into the shuffling machine exactly as it came, stacked from at the top down to . Frank wants to use what he knows about the machine to work out which card sits at position from the top once the shuffle is over.
Input
The first line holds the number of test cases . Each test case then follows in this format.
M C W
A1 B1
...
AC BC
The first line holds three integers , , separated by a single space, where is the number of cards, is the number of cuts, and is the position Frank asks about. Each of the next lines holds two integers , separated by a single space, meaning that cut moves the cards starting at the -th card from the top to the top of the pile.
Constraints
Output
For each test case, print one line in this form.
Case #X: P
is the test case number starting from , and is the card at position from the top of the pile after the shuffle.