Shuffling Cards
Time limit1sMemory limit128 MB
Decide whether permutation b equals some power a^k of permutation a with k greater than 1.
- Level
Medium6 of 10
- Topics
- Math, Combinatorics, Implementation
- Solved
- No attempts yet
Problem
Bajtazar gave his son Bajtek a deck of cards as a present. The deck has cards, numbered from to .
Bajtek loved the gift. He spent the whole evening in his room shuffling the deck, and he grew so practiced that every shuffle came out exactly the same way: during a shuffle the card at position (for ) always moved to position (with ).
At some point Bajtek's father came in and said it was time for bed. Bajtek begged him to show, one last time before sleep, how cards should really be shuffled. So Bajtazar shuffled them so that the card at position ended up at position (again ).
Bajtek admired how skillfully his father shuffled and wished he could do the same. He is still little, though, and cannot shuffle the way his father does. But he had an idea: he will repeat his own shuffle several times, hoping that in the end the deck ends up in the same arrangement as after his father's shuffle.
Now the boy cannot fall asleep, wondering whether this is even possible. Help him!
In other words, decide whether the permutation can be obtained by applying the permutation some number of times greater than one.
Input
The first line contains a single integer (). The second and third lines describe the permutations and : each is a sequence of pairwise distinct integers from to . You may assume that the two permutations are different.
Output
Print a single word: TAK if there exists an integer such that repeating Bajtek's shuffle times produces exactly Bajtazar's shuffle, or NIE otherwise. (TAK and NIE are the Polish words for "yes" and "no".)