The Bessie Shuffle
Time limit1sMemory limit128 MB
Repeatedly shuffle the top M cards by a fixed permutation, deal the top card onto a pile, and report the labels at queried pile positions.
- Level
Medium7 of 10
- Topics
- Simulation, Math
- Solved
- No attempts yet
Problem
Bessie is practicing her card tricks. She has already mastered the Bessie shuffle, a shuffle on cards that moves the -th card from the top to position from the top.
Now Bessie practices on a bigger deck. The deck holds cards labeled through . She takes the top cards, performs the Bessie shuffle on them, and puts the shuffled cards back on top of the deck. She then removes the top card and places it face down. She repeats this until the deck runs out. Each card she removes goes on top of the cards she has already put down. Once fewer than cards are left she stops shuffling and only keeps moving the top card onto the pile.
The deck starts in sorted order with on top, next and at the bottom. Given the description of the Bessie shuffle, compute the label of the card that ends up at each of the positions of the finished pile, counted from its top.
Input
The first line contains , and separated by spaces (, ).
Each of the next lines holds , the position that the -th card from the top moves to during the Bessie shuffle (). is a permutation of through .
Each of the following lines holds one query ().
Output
Print lines. Line holds the label of the card at position from the top of the finished pile.
Hint
Take five cards stacked as from the top, with a shuffle on three cards that sends the top card to the bottom. The process runs like this:
- , put face down
- , put face down
- , put face down
- , fewer than three cards remain, so put face down with no shuffle
- , put face down
The finished pile reads from the top.