Card Trick
Time limit2sMemory limit128 MB
Given the cards on the observed hopping path, compute the chance that a random start among positions 1 to 10 ends on the same final card.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Probability, Math
- Solved
- No attempts yet
Problem
I am learning card tricks to impress my girlfriend Alice. My latest trick is a probabilistic one, so it works in most cases but not in every case.
To perform the trick I first shuffle many playing cards and lay them out in one line, faces up, on the table. There are at least ten cards on the table. Alice secretly selects one of the first ten cards, that is, she chooses a secret number between 1 and 10 inclusive. From there she skips cards repeatedly. After selecting the card at position , whose face shows the value , she selects the card at position . J, Q, K count as 10 and A counts as 11.
Alice stops as soon as there is no card at position .
I then run the same procedure from a randomly selected starting position, which may differ from the position Alice selected. It turns out that I often end up on the same card she does. Alice is very impressed by the trick.
The math behind it interests me more. Given my randomly selected starting position and the faces of every card I selected, including my final one, compute the probability that Alice chose a starting position that ends on the same final card. Assume her starting position is chosen with uniform probability between 1 and 10 inclusive.
I forgot to note the cards I skipped, so those cards are unknown. Assume the face of every unknown card is independent of the other faces and uniform over the possible faces (2 to 10, J, Q, K, A).
The number of unknown cards behind my final selected card is smaller than the value of that card. If my final card is a Q, then 0 to 9 unknown cards follow it.
Input
The input holds several test cases and continues to the end of the file. Each test case is given as follows.
- One line with two integers and (, ), where is the number of cards I selected and is the position of my first selected card, counted from 1.
- One line with tokens that give the faces of the selected cards in the order I selected them, including the final card. Each face is either an integer () or one of the characters J, Q, K, A.
Output
For each test case, print on one line the probability that Alice chooses a starting position leading to the same final card.
The probability is a rational number . Under the constraints above is never a multiple of , so exactly one integer with satisfies . Print that . For a probability of exactly , print .