Time limit
2s
Memory limit
128 MB
There are N cards whose initial positions are numbered from 0 to N-1. When the cards are dealt in their current order to players 0, 1, and 2, the card at position j goes to player j mod 3.
The card that was initially at position i must eventually be dealt to player P[i].
One shuffle method is given as a permutation S of length N. After one shuffle, the card currently at position i moves to position S[i].
Find the minimum number of shuffles needed to satisfy the target distribution.
The first line contains N. N is a multiple of 3 and satisfies 3 <= N <= 48.
The second line contains the sequence P of length N. Each element of P is one of 0, 1, and 2.
The third line contains the sequence S of length N. Each element of S is an integer from 0 to N-1, and no value appears more than once.
Print the minimum number of shuffles needed to satisfy the target distribution. If it can never be satisfied, print -1.