#K51947. Minimum Swap Operations to Match Arrays

    ID: 29200 Type: Default 1000ms 256MiB

Minimum Swap Operations to Match Arrays

Minimum Swap Operations to Match Arrays

You are given two arrays of characters, source and target, each containing n characters. Your task is to determine the minimum number of swap operations required to transform the source array into the target array.

A swap operation exchanges the positions of two characters in the source array. Formally, you need to find the minimum number of operations such that after these operations, the following holds: $$\text{source} = \text{target},$$ provided that $$sorted(source)=sorted(target).$$

If it is not possible to achieve the transformation because the arrays have different multisets of characters, output -1. If the arrays are already identical, output 0.

Note: It is guaranteed that if a transformation is possible, the number of mismatched positions will be even, so a simple pairing strategy will yield the minimum number of swaps.

inputFormat

The input is given via standard input (stdin) and consists of three lines:

  1. The first line contains a single integer n, the number of characters in each array.
  2. The second line contains n space-separated characters representing the source array.
  3. The third line contains n space-separated characters representing the target array.

It is guaranteed that 1 ≤ n ≤ 105.

outputFormat

Output a single integer to standard output (stdout) — the minimum number of swap operations required to transform the source array into the target array. If the transformation is impossible, output -1.## sample

4
a b c d
b a d c
2