Shuffle
Time limit3sMemory limit128 MB
Given a permutation b and an integer l, count the permutations a whose l-th iterate equals b, modulo 1e9+7.
- Level
Medium7 of 10
- Topics
- Combinatorics, Math, Number theory, Simulation
- Solved
- No attempts yet
Problem
Byteasar owns a deck of cards. The slots that hold the cards are numbered through . He has practiced one particular shuffle so thoroughly that it always rearranges the deck in exactly the same way: whatever card sits in slot is moved to slot . Because every card lands in a distinct slot, the sequence is a permutation of .
Byteasar applies this same shuffle times in a row. Write for the slot that ends up holding the card which started in slot . Formally, set and for ; then .
You are told , , and the whole sequence . Count how many shuffles are consistent with what Byteasar saw, that is, how many permutations satisfy for every . The number of such shuffles can be enormous, so report it modulo . If no shuffle can produce , the answer is .
Input
The first line contains two integers and (). Each of the next lines contains a single integer: the -th of them is (), the slot holding the card from slot after the shuffle has been repeated times. The values are guaranteed to form a permutation of .
Output
Print one integer: the number of shuffles (permutations of ) for which repeating exactly times yields the given sequence , taken modulo . Print if no such shuffle exists.