A minimum sorting

4.3

3 votes
Dynamic Programming and Bit Masking, Bitmask, Dynamic Programming, Algorithms
Problem

You are given two arrays A and B of size N. Your task is to sort array A (non-decreasing) by using the following operation for the minimum number of times.

Operation steps are: 

  1. Select any index i such that 1i<N.
  2. Swap Ai and Bi+1.
  3. Swap Ai+1 and Bi.

If there is a way to sort array A using the above operation, then find the minimum number of operations that must be performed. If it is impossible to sort the array, then print -1.

Input format

  • The first line contains an integer T denoting the number of test cases. For each test case:
  • The first line of each test case contains an integer N denoting the number of elements in arrays A and B.
  • The second line of each test case contains N space-separated integers of array A.
  • The third line of each test case contains N space-separated integers of array B.

Output format

For each test case, print a single line indicating the minimum number of operations if sorting can be done. If it is not possible to sort the array, print -1.

Constraints

1T5

1N16

1Ai,Bi100

Sample Input
3
3
1 2 2
4 5 8
2
8 7
7 8
3
2 3 2
2 1 2
Sample Output
0
-1
1
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

First test case:
                       The array A is already sorted, so we don't need to perform any operation.


Second test case:
                       The array A is initially not sorted, A={8,7} and B={7,8}, we need to perform operation. We have no other choice than choosing index as 1, according to operation we need to swap A1 and B2 and swap A2 and B, after performing  array A={8,7} and B={7,8} remains the same and we have no other options, so it is impossible to sort the array.

Third test case:
                       
A={2,3,2} and B={2,1,2} and let us choose i=1, according to operation we need to swap A1 and B2 and swap A2 and B, after performing  array A={1,2,2} and B={3,2,2} and now note that array A is sorted. Number of operations in this case are 1.

Editor Image

?