Shuffle
Time limit1sMemory limit128 MB
After applying m shuffles to an ordered deck of n cards, count how many cards numbered r or less fall in positions p through q. n is up to 1e9, so the huge deck must be tracked implicitly.
- Level
Medium7 of 10
- Topics
- Combinatorics, Math, Implementation, Intervals
- Solved
- No attempts yet
Problem
There are cards numbered through . Initially they are stacked in order so that the top card is number , the second from the top is number , …, and the bottom card is number .

The deck is rearranged by an operation called shuffle, where and are integers with .
- shuffle
- Split the cards into three piles: pile consisting of the top cards, pile consisting of the cards from position to , and pile consisting of the cards from position to . Then place pile on top of pile , and place pile on top of that.
For example, applying shuffle to ordered cards makes the numbers, from top to bottom, .

Starting from the initial deck, perform shuffles shuffle, shuffle, …, shuffle in order. Write a program that, in the resulting deck, counts how many cards numbered or less lie among the cards from position to position counted from the top.
Input
The input consists of lines.
- Line : the number of cards ().
- Line : the number of shuffles ().
- Line : three integers (, ).
- Line (for ): two integers and () separated by a space.
Output
Output the number of cards numbered or less among the cards from position to position (counted from the top) in the deck after the shuffles.
Notes
Applying shuffle to a deck of cards makes the cards, from top to bottom, . Among positions through from the top, the cards numbered or less are number and number — cards.
Applying shuffle, shuffle, shuffle in order to a deck of cards makes the cards, from top to bottom, . Among positions through from the top, there are cards numbered or less.