#C11938. Minimum Swaps to Equal Strings

    ID: 41309 Type: Default 1000ms 256MiB

Minimum Swaps to Equal Strings

Minimum Swaps to Equal Strings

You are given two strings a and b of length n. Your task is to transform string a into string b using a sequence of swap operations on string a only. In one swap operation, you can choose any two indices i and j (with 0 ≤ i, j < n and i ≠ j) and swap the characters a[i] and a[j]. The goal is to achieve a == b using as few swaps as possible. If it is impossible to transform a into b (i.e. if sorted(a) \neq sorted(b)), output -1 instead.

It can be shown that if the transformation is possible, the minimum number of swaps needed is well-defined. Formally, if the transformation is possible then the answer is the minimum number k such that there exists a sequence of swap operations that transforms a into b in k moves.

In mathematical terms, if we let S be the set of valid swap operations and define an operation on string a as

[ a' = swap(a, i, j)]

for some (i, j) (\in S), then we require to find the minimum k such that there exist indices (i1,j1), (i2,j2), ..., (ik,jk) with

[ a^{(k)} = swap(\dots swap(a, i_1, j_1) \dots , i_k, j_k) = b]

and if no such sequence exists output -1.

inputFormat

The input is read from standard input (stdin) and has the following format:

  • The first line contains a single integer n (the length of the strings).
  • The second line contains the string a.
  • The third line contains the string b.

outputFormat

Output the minimum number of swap operations required to transform string a into string b on a single line. If it is impossible, output -1.

## sample
5
abacb
bcaba
2