#C5193. Minimum Moves to Reorder Array

    ID: 48815 Type: Default 1000ms 256MiB

Minimum Moves to Reorder Array

Minimum Moves to Reorder Array

You are given two arrays: an initial arrangement and a target arrangement. In one move, you can perform a rotation on the array; that is, you can take either the first element and move it to the end (left rotation) or take the last element and move it to the beginning (right rotation).

The task is to determine the minimum number of such moves required to transform the initial array into the target array. A rotation by k positions on the left transforms the array into:

\( [a_{k+1}, a_{k+2}, \dots, a_{n}, a_{1}, \dots, a_{k}] \)

Similarly, a right rotation by \( k \) positions yields:

\( [a_{n-k+1}, a_{n-k+2}, \dots, a_{n}, a_{1}, \dots, a_{n-k}] \)

Note that if the target arrangement is not a rotation of the initial arrangement (i.e. their multisets differ or the order cannot be obtained solely by rotations), the answer is \( -1 \). If the array is already in the target arrangement, no moves are needed.

For a valid rotation that obtains the target, if the number of moves needed when rotating left is \( k \), then the corresponding right rotation would be \( n-k \). Hence, the answer is \( \min(k, n-k) \), where \( n \) is the size of the array.

inputFormat

The first line contains an integer \( n \) denoting the number of elements in the arrays.

The second line contains \( n \) space-separated integers representing the initial array.

The third line contains \( n \) space-separated integers representing the target array.

outputFormat

Output a single integer which is the minimum number of moves required to transform the initial arrangement into the target arrangement. If it is impossible, output -1.

## sample
5
1 2 3 4 5
3 4 5 1 2
2