#K77582. Minimum Swaps to Transform Sequence
Minimum Swaps to Transform Sequence
Minimum Swaps to Transform Sequence
You are given an integer \(N\) and two sequences of integers of length \(N\): an initial sequence and a target sequence. Your task is to determine the minimum number of swap operations required to transform the initial sequence into the target sequence. A swap operation exchanges two elements in the sequence. If it is impossible to transform the initial sequence into the target sequence (i.e. the two sequences do not have the same set of elements), output \(-1\).
The problem can be solved by mapping the elements of the initial sequence to their corresponding indices in the target sequence. Then, by detecting cycles in this mapping, the minimum number of swaps needed for each cycle of length \(L\) is \(L-1\). The total number of swaps is the sum of the swaps required for all cycles.
Note: All formulas are given in LaTeX format.
inputFormat
The input is provided via standard input (stdin) and has the following format:
N initial[0] initial[1] ... initial[N-1] target[0] target[1] ... target[N-1]
where:
N
is an integer representing the length of the sequences.- The second line contains \(N\) space-separated integers representing the initial sequence.
- The third line contains \(N\) space-separated integers representing the target sequence.
outputFormat
Output a single integer to standard output (stdout) representing the minimum number of swaps required to transform the initial sequence into the target sequence. If the transformation is not possible, output \(-1\).
## sample5
3 1 2 4 5
1 2 3 4 5
2