#C6544. Minimum Adjacent Swaps to Transform into Anagram

    ID: 50316 Type: Default 1000ms 256MiB

Minimum Adjacent Swaps to Transform into Anagram

Minimum Adjacent Swaps to Transform into Anagram

You are given two strings S and T of length N. Your task is to determine the minimum number of adjacent swaps required to transform S into T so that they become anagrams of each other. In one operation, you can swap two adjacent characters in S.

Two strings are anagrams if they contain the exact same characters with the same frequencies. If it is impossible to transform S into T (i.e. they are not anagrams), output -1.

The minimum number of swaps is computed by sequentially bringing each character of S to its correct position to match T by performing a series of adjacent swaps.

Note: The order of characters in T represents the target order. Only adjacent swaps are allowed, and each swap counts as a single operation. The solution must process multiple test cases with input given from standard input and output the result for each test case to standard output.

inputFormat

The first line contains an integer T (1 ≤ T ≤ 100), the number of test cases. For each test case, the input is given in the following format:

  1. An integer N (1 ≤ N ≤ 103), the length of the strings.
  2. A string S of length N.
  3. A string T of length N.

All input is read from standard input (stdin).

outputFormat

For each test case, print a single integer representing the minimum number of adjacent swap operations required to transform S into T. If it is impossible, print -1.

Output each result on a new line to standard output (stdout).

## sample
5
3
abc
bca
4
abcd
bcda
5
abcde
fghij
2
ab
ba
6
abcdef
fedcba
2

3 -1 1 15

</p>