The Bessie Shuffle
Time limit1sMemory limit128 MB
Shuffle the top M cards with the given permutation, move the top card to a pile, repeat until empty, and report the card at each queried pile position.
- 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 rearranges them so the -th card from the top becomes the -th card from the top.
Now Bessie practices on a bigger deck. It holds cards () labeled to . She takes the top cards, performs the Bessie shuffle on them, and puts them back on top of the deck. She then removes the top card and places it face down. She repeats this, stacking each removed card on top of the ones she has already placed, until the deck is empty. Once fewer than cards are left she stops shuffling, but she keeps moving the top card onto the pile.
The deck starts sorted, with on top, next and on the bottom. Given the Bessie shuffle, answer queries (, ): which card ends up at position from the top of the finished pile?
Input
The first line contains , and separated by spaces.
Each of the next lines contains one integer. Line holds , the position that the -th card from the top moves to in the Bessie shuffle (). The values through use each of through exactly once.
Each of the next lines contains one integer , the -th query (). It asks for the card at position from the top of the finished pile.
Output
Print lines. On line , print the label of the card at position from the top of the finished pile.
Hint
In the first example Bessie has cards ordered . Her shuffle works on cards and moves the top card of the window to the bottom. The deck changes like this:
- , then goes face down
- , then goes face down
- , then goes face down
- , then goes face down
- , then goes face down
The finished pile reads from the top.