Problem:
Score : 700 points

Problem Statement

We have N cards numbered 1, 2, ..., N.
Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side.
Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up.

Determine whether it is possible to have a non-decreasing sequence facing up from left to right (that is, for each i (1 \leq i \leq N - 1), the integer facing up on the (i+1)-th card from the left is not less than the integer facing up on the i-th card from the left) by repeating the operation below. If the answer is yes, find the minimum number of operations required to achieve it.

Choose an integer i (1 \leq i \leq N - 1).
Swap the i-th and (i+1)-th cards from the left, then flip these two cards.

Constraints

1 \leq N \leq 18

1 \leq A_i, B_i \leq 50 (1 \leq i \leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If it is impossible to have a non-decreasing sequence, print -1.
If it is possible, print the minimum number of operations required to achieve it.

Sample Input 1

3
3 4 3
3 2 3

Sample Output 1

1

By doing the operation once with i = 1, we have a sequence [2, 3, 3] facing up, which is non-decreasing.

Sample Input 2

2
2 1
1 2

Sample Output 2

-1

After any number of operations, we have the sequence [2, 1] facing up, which is not non-decreasing.

Sample Input 3

4
1 2 3 4
5 6 7 8

Sample Output 3

0

No operation may be required.

Sample Input 4

5
28 15 22 43 31
20 22 43 33 32

Sample Output 4

-1

Sample Input 5

5
4 46 6 38 43
33 15 18 27 37

Sample Output 5

3

Solution in C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include <bits/stdc++.h>
using namespace std;
int C[2][18]={};

string vec_to_str(vector<int> v){
string s=""; int L=v.size();
for(int i=0; i<L; i++){
  s+=to_string(v[i]);
  if(i<L-1){ s+=","; }
}
return s;
}

vector<int> mut(vector<int> v, int p){
int L=v.size()/2; vector<int> w(2*L);
for(int i=0; i<L; i++){ 
 if(i==p){
   w[i]=v[i+1]; w[i+1]=v[i];
   w[L+i]=(v[L+i]+1)%2; w[L+i+1]=(v[L+i+1]+1)%2;
   i++; continue;
 }
w[i]=v[i]; w[L+i]=v[L+i];
}
return w;
}  

bool hante(vector<int> v){
for(int i=1, L=v.size()/2; i<L; i++){
if(C[v[L+i-1]][v[i-1]]>C[v[L+i]][v[i]]){ return false; }
}
return true;
}

int main(){
int N, i, j, ans=0; cin >> N;
for(i=0; i<N; i++){ cin >> C[0][i]; }
for(i=0; i<N; i++){ cin >> C[1][i]; }

vector<int> st(2*N);
for(i=0; i<N; i++){ st[i]=i; st[N+i]=0; }
vector< vector<int> > V={st}; map<string, int> D; vector<int> R={0};
if(hante(st)){ cout << 0 << "\n"; return 0; }
  
for(i=0; i<V.size(); i++){
  for(j=0; j<N-1; j++){
   vector<int> M=mut(V[i], j); string S=vec_to_str(M);
   if(D[S]){ continue; }
   if(hante(M)){ cout << R[i]+1 << "\n"; return 0; }
   V.push_back(M); D[S]=1; R.push_back(R[i]+1);
  }
}
  
cout << -1 << "\n";
}