Walk Swapping
Time limit1sMemory limit2048 MB
Given initial and final coin arrangements on a cycle, find the fewest swaps along a walk that turns one into the other, or report -1 if impossible.
- Level
Hard8 of 10
- Topics
- Array, Prefix sum, Greedy
- Solved
- No attempts yet
Problem
A cycle with vertices is a graph in which vertices and are connected by an edge for , and vertices and are connected by an edge. The vertices of are numbered 1 to .
There are coins, and each coin is numbered with one of . Two coins may have the same number. Initially, each vertex of holds one coin. Two vertices can swap their coins with each other.
For a walk in , a walk swapping swaps the coins on and in the order . A walk is a sequence of () vertices in which consecutive vertices are different and adjacent in . You can think of a walk as the vertices visited when you traverse . The number is the length of . A walk of length causes swaps, and a walk of length one causes no swap.
The figure below shows the walk swapping for the walk on a cycle with 4 vertices.

For example, the walk in the figure causes 3 swaps. The same final configuration is reached by the walk with only one swap.
You are given the initial and final configurations of coins. Find a walk swapping that turns the initial configuration into the final one with the minimum total number of swaps.
Input
The first line contains an integer (), the number of vertices in .
The second line contains integers between 1 and . The -th integer is the coin on vertex in the initial configuration. Values may repeat.
The third line contains integers between 1 and in the same format, giving the coin on each vertex in the final configuration.
Output
Print exactly one line containing the minimum number of swaps in a walk swapping that turns the initial configuration into the final one. If no walk swapping can do this, print -1.