Problem G
Deck Randomisation

Alice and Bob love playing Don’tminion, which typically involves a lot of shuffling of decks of different sizes. Because they play so often, they are not only very quick at shuffling, but also very consistent. Each time Alice shuffles her deck, her cards get permuted in the same way, just like Bob always permutes his cards the same way when he shuffles them. This isn’t good for playing games, but raises an interesting question.
They know that if they take turns shuffling, then at some point the deck will end up ordered in the same way as when they started. Alice shuffles once first, then Bob shuffles once, then Alice shuffles again, et cetera. They start with a sorted deck. What they do not know, however, is how many shuffles it will take before the deck is sorted again.
Can you help them compute how many shuffles it will take? As
Alice and Bob can only do
Input
-
The first line contains a single integer
, the number of cards in the deck. -
The second line contains
distinct integers , where is the new position of the card previously at position when Alice shuffles the deck. -
The third line contains
distinct integers , where is the new position of the card previously at position when Bob shuffles the deck.
Output
-
Output a single positive integer
, the minimal number of shuffles required to sort the deck, or huge when this number is strictly larger than .
Sample Input 1 | Sample Output 1 |
---|---|
3 2 3 1 3 1 2 |
2 |
Sample Input 2 | Sample Output 2 |
---|---|
6 5 1 6 3 2 4 4 6 5 1 3 2 |
5 |
Sample Input 3 | Sample Output 3 |
---|---|
8 1 4 2 6 7 8 5 3 3 6 8 4 7 1 5 2 |
10 |