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 (Python):
N = int(input())
A = [int(a) for a in input().split()]
B = [int(b) for b in input().split()]

L = [[0]*2 for _ in range(N)]

for i in range(N):
    L[i][i%2] = A[i]
    L[i][(i+1)%2] = B[i]

P = [int(i) for i in range(N)]

ans = 10**10
import itertools
for C in itertools.combinations(P, (N+1)//2):
    C = list(C)
    used = [0]*N
    for i in C:
        used[i] = 1
    B_temp = []
    for i in range(N):
        if used[i] == 0:
            B_temp.append((L[i][1], i))

    temp = [0]*N
    check = [0]*N
    B_temp.sort()
    for i in range(len(C)):
        C[i] = (L[C[i]][0], C[i])
    C.sort()
    j = 0
    k = 0
    for i in range(N):
        if i%2 == 0:
            temp[i] = C[j][1]
            check[i] = C[j][0]
            j += 1
        else:
            temp[i] = B_temp[k][1]
            check[i] = B_temp[k][0]
            k += 1
    if check != sorted(check):
        continue

    cnt = 0
    for i in reversed(range(N)):
        for j in range(i):
            if temp[j] > temp[j + 1]:
                temp[j], temp[j + 1] = temp[j + 1], temp[j]
                cnt += 1

    ans = min(ans, cnt)

if ans == 10**10:
    ans = -1
print(ans)

Solution (Python):
import sys
input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ans=10**9
def bubble_sort(arr):
    change = True
    num=0
    while change:
        change = False
        for i in range(len(arr) - 1):
            if arr[i] > arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
                change = True
                num+=1
    return num
for i in range(2**n):
    even=[]
    odd=[]
    for j in range(n):
        x=(i>>j)%2
        if j%2==0:
            if x==0:
                even.append((a[j],j))
            else:
                odd.append((b[j],j))
        else:
            if x==0:
                odd.append((a[j],j))
            else:
                even.append((b[j],j))
    if len(odd)!=n//2:
        continue
    even.sort()
    odd.sort()
    check=True
    order=[]
    new=[]
    for j in range(n//2):
        order.append(even[j][1])
        order.append(odd[j][1])
        new.append(even[j][0])
        new.append(odd[j][0])
    if n%2!=0:
        new.append(even[-1][0])
        order.append(even[-1][1])
    for j in range(n-1):
        if new[j]>new[j+1]:
            check=False
    if not check:
        continue
    x=bubble_sort(order)
    ans=min(ans,x)
if ans==10**9:
    print(-1)
else:
    print(ans)

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
lst=[]
for i in range(2**N):
    h=[[],[]]
    for j in range(N):
        if (i>>j)&1==1:
            h[(j+1)%2].append([B[j],j])
        else:
            h[j%2].append([A[j],j])
    if len(h[1])==N//2:
        lst.append(h)
lsls=[]
for h in lst:
    h[0].sort()
    h[1].sort()
    cnt=h[0][0][1]
    for i in range(N-1):
        if h[i%2][i//2][0]>h[(i+1)%2][(i+1)//2][0]:
            break
    else:
        hhh=[]
        for i in range(N):
            hhh.append(h[i%2][i//2][1])
        lsls.append(hhh)
inf=float("inf")
ans=inf
if lsls:
    for h in lsls:
        flag=[0]*N
        cnt=0
        for u in h:
            flag[u]=1
            cnt+=sum(flag[u+1:])
        ans=min(ans,cnt)
if ans==inf:
    print(-1)
else:
    print(ans)

Solution (Python):
n = int(input())
al = list(map(int,input().split()))
bl = list(map(int,input().split()))

def bubble_sort(lst):
    a = 0
    for i in range(len(lst)-1):
        for j in range(len(lst)-1, i, -1):
            if lst[j-1] > lst[j]:
                tmp = lst[j]
                lst[j] = lst[j-1]
                lst[j-1] = tmp
                a += 1
    return a

anss = float("inf")
for i in range(2 ** n):
    bits = [0] * n
    for j in range(n):
        if ((i >> j) & 1):
            bits[j] = 1
    even_odd = [[], []]
    for idx, bit in enumerate(bits):
        if bit == 0:
            even_odd[(idx + bit) % 2].append((al[idx], idx))
        else:
            even_odd[(idx + bit) % 2].append((bl[idx], idx))
    if len(even_odd[0]) - len(even_odd[1]) != n % 2:
        continue
    aal = sorted(even_odd[0])
    bbl = sorted(even_odd[1])
    goto = []
    now = 0
    for k in range(n):
        if k % 2 == 0:
            tmp, idx = aal.pop(0)
            if now <= tmp:
                goto+= [idx]
                now = tmp
            else:
                break
        else:
            tmp, idx = bbl.pop(0)
            if now <= tmp:
                goto+= [idx]
                now = tmp
            else:
                break
    else:
        ans = bubble_sort(goto)
        anss = min(anss, ans)

if anss == float('inf'):
    print(-1)
else:
    print(anss)

Solution (Python):
import sys
readline = sys.stdin.readline
class BIT:
    
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
        self.p = 2**(n.bit_length() - 1)
        self.dep = n.bit_length()
    def get(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
    
    def bl(self, v):
        if v <= 0:
            return -1
        s = 0
        k = self.p
        for _ in range(self.dep):
            if s + k <= self.size and self.tree[s+k] < v:
                s += k
                v -= self.tree[s+k]
            k //= 2
        return s + 1

def count(P):
    res = 0
    T = BIT(N)
    Pi = [None]*N
    for i in range(N):
        Pi[P[i]] = i
    for i in range(N):
        p = Pi[i]
        res += i-T.get(p+1)
        T.add(p+1, 1)
    return res
 

N = int(readline())
A = list(map(int, readline().split()))
B = list(map(int, readline().split()))
uhalf = -(-N//2)
dhalf = N - uhalf
inf = 10**9+7
ans = inf
for S in range(1<<N):
    card = [A[i] if S&(1<<i) else B[i] for i in range(N)]
    parity = [(1&(S>>i))^(i&1) for i in range(N)]
    even = [(card[i], i) for i in range(N) if parity[i]]
    odd = [(card[i], i) for i in range(N) if not parity[i]]
    if len(even) != uhalf or len(odd) != dhalf:
        continue
    even.sort()
    odd.sort()
    if any(e[0] > o[0] for e, o in zip(even, odd)) or any(e[0] < o[0] for e, o in zip(even[1:], odd)):
        continue
    perm = [even[i//2][1] if not i&1 else odd[i//2][1] for i in range(N)]
    ans = min(ans, count(perm))
print(ans if ans < inf else -1)

Solution (Python):

class BIT():
    """一点加算、区間取得クエリをそれぞれO(logN)で答える
    add: i番目にvalを加える
    get_sum: 区間[l, r)の和を求める
    i, l, rは0-indexed
    """
    def __init__(self, n):
        self.n = n
        self.bit = [0] * (n + 1)

    def _sum(self, i):
        s = 0
        while i > 0:
            s += self.bit[i]
            i -= i & -i
        return s

    def add(self, i, val):
        """i番目にvalを加える"""
        i = i + 1
        while i <= self.n:
            self.bit[i] += val
            i += i & -i

    def get_sum(self, l, r):
        """区間[l, r)の和を求める"""
        return self._sum(r) - self._sum(l)


from operator import itemgetter
from collections import deque

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 10**18


for bit_state in range(1 << n):
    pattern = [[] for i in range(2)]
    for i in range(n):
        if bit_state & (1 << i) and i % 2 == 0:
            pattern[0].append(a[i]*100 + i)
        elif bit_state & (1 << i) and i % 2 == 1:
            pattern[1].append(a[i]*100 + i)
        elif i % 2 == 0:
            pattern[1].append(b[i]*100 + i)
        else:
            pattern[0].append(b[i]*100 + i)

    if len(pattern[0]) == len(pattern[1]) or len(pattern[0]) - 1 == len(pattern[1]):
        for i in range(2):
            pattern[i] = sorted(pattern[i])
        bit = BIT(n)
        ans_tmp = 0
        prev_num = 10**8
        for i in range(n)[::-1]:
            pal = i % 2
            num = pattern[pal].pop()
            ind = num % 100
            num = num // 100
            if prev_num < num:
                break
            prev_num = num
            bit.add(ind, 1)
            ans_tmp += bit.get_sum(0, ind)
        else:
            ans = min(ans, ans_tmp)

if ans == 10**18:
    print(-1)
else:
    print(ans)

Solution (Python):


import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read





n = int(input())
a = [int(i)-1 for i in readline().split()]
b = [int(i)-1 for i in readline().split()]

N = 1<<n
ans = INF = 10**9
for mask in range(N):
    bucket = [[] for _ in range(50)]
    for i in range(n):
        bucket[a[i] if mask&(1<<i) else b[i]].append(i)
    
    cnt = 0
    res = []
    
    
    for bi in bucket:
        if not bi: continue
        l = len(bi)
        o = [i for i in bi if ((mask>>i)^i)&1==0]
        e = [i for i in bi if ((mask>>i)^i)&1==1]
        odd = len(o)
        even = len(e)
        
        if l%2 == 0:
            if odd != even: break
        else:
            if cnt%2==0:
                if even != odd+1: break
            else:
                if odd != even+1: break
        
        
        for i in range(l):
            res.append(e[i//2] if (i+cnt)%2==0 else o[i//2])
        cnt += l
        
        
    else: 
        num = 0
        for i in range(n):
            for j in range(i+1,n):
                if res[i] > res[j]: num += 1
        
        ans = min(ans,num)                

if ans == INF: print(-1)
else: print(ans)

Solution (Python):

def merge(arr, temp, left, mid, right): 
    inv_count = 0
  
    i = left 
    j = mid 
    k = left 
    while ((i <= mid - 1) and (j <= right)): 
        if (arr[i] <= arr[j]): 
            temp[k] = arr[i] 
            k += 1
            i += 1
        else: 
            temp[k] = arr[j] 
            k += 1
            j += 1
  
            
            
            inv_count = inv_count + (mid - i) 
  
    
    
    while (i <= mid - 1): 
        temp[k] = arr[i] 
        k += 1
        i += 1
  
    
    
    while (j <= right): 
        temp[k] = arr[j] 
        k += 1
        j += 1
  
    
    for i in range(left,right+1,1): 
        arr[i] = temp[i] 
  
    return inv_count 
  



def _mergeSort(arr, temp, left, right): 
    inv_count = 0
    if (right > left): 
        
        
        
        mid = int((right + left)/2) 
  
        
        
        
        inv_count = _mergeSort(arr, temp, left, mid) 
        inv_count += _mergeSort(arr, temp, mid+1, right) 
  
        
        inv_count += merge(arr, temp, left, mid+1, right) 
  
    return inv_count 
  


def countSwaps(arr, n): 
    temp = [0 for i in range(n)] 
    return _mergeSort(arr, temp, 0, n - 1) 


from itertools import combinations, zip_longest

N = int(input())

A = list(map(int,input().split()))
B = list(map(int,input().split()))

cards = [(a,b) if i % 2 == 0 else (b,a) for i,(a,b) in enumerate(zip(A,B))]

best = float('inf')

for odd_indices in combinations(range(N), N//2):
    odds = sorted((cards[i][1], i) for i in odd_indices)
    evens = sorted((card[0], i) for i,card in enumerate(cards) if i not in odd_indices)


    union = []
    for e,o in zip_longest(evens,odds):
        union.append(e)
        if o is not None:
            union.append(o)
    if all(a <= b for (a,_),(b,_) in zip(union,union[1:])):
        indices = [i for _,i in union]
        best = min(best, countSwaps(indices, N))

if best == float('inf'):
    print(-1)
else:
    print(best)

Solution (Python):
from itertools import combinations

N = int(input())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]

ret = float('inf')
for ce in combinations(range(N), (N + 1) // 2) :
  e, o = [], []
  for i in range(N) :
    if i in ce :
      if i % 2 == 0 :
        e.append([A[i], i])
      else :
        e.append([B[i], i])
    else :
      if i % 2 == 0 :
        o.append([B[i], i])
      else :
        o.append([A[i], i])
  
  e.sort()
  o.sort()
  s = []
  for i in range(N // 2) :
    s.append(e[i])
    s.append(o[i])
  if N % 2 != 0 :
    s.append(e[N // 2])
  
  for i in range(1, N) :
    if s[i][0] < s[i-1][0] :
      break
    
  else :
    tmp = 0
    for i in range(N) :
      for j in range(i) :
        if s[j][1] > s[i][1] :
          tmp += 1
    ret = min(ret, tmp)
    
if ret == float('inf') :
  print(-1)
else :
  print(ret)

Solution (Python):
from itertools import *
def count_inversion(sequence):
    return sum(sum(m<n for m in sequence[i+1:]) for i,n in enumerate(sequence))

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

up = []
down = []
for i in range(n):
    if i % 2 == 0:
        up.append((a[i], i))
        down.append((b[i], i))
    else:
        up.append((b[i], i))
        down.append((a[i], i))

up.sort()
l = set([i for i in range(n)])

ans = 10000
for u in combinations(up, (n+1)//2):
    index = []
    value = []
    for val, ind in u:
        index.append(ind)
        value.append(val)

    d_index = l - set(index)
    d = []
    for i in d_index:
        d.append(down[i])
    d.sort()
    value.append(100)
    flag = 1
    for i in range(len(d)):
        if not value[i] <= d[i][0] <= value[i+1]:
            flag = 0
            break
    if flag == 0:
        continue

    for i in range(len(d)):
        index.insert(2*i+1, d[i][1])

    ans = min(ans, count_inversion(index))



if ans == 10000:
    print(-1)
else:
    print(ans)

Solution (Python):

class BITbisect():
    def __init__(self, max):
        self.max = max
        self.data = [0]*(self.max+1)
    
    
    
    def query_sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    
    
    def add(self, i, x):
        while i <= self.max:
            self.data[i] += x
            i += i & -i

    def insert(self, x):
        self.add(x, 1)

    def delete(self, x):
        self.add(x, -1)

    def count(self, x):
        return self.query_sum(x) - self.query_sum(x-1)
    
    def length(self):
        return self.query_sum(self.max)
    
    
    
    def search(self, c):
        c += 1
        s = 0
        ind = 0
        l = self.max.bit_length()
        for i in reversed(range(l)):
            if ind + (1<<i) <= self.max:
                if s + self.data[ind+(1<<i)] < c:
                    s += self.data[ind+(1<<i)]
                    ind += (1<<i)
        if ind == self.max:
            return False
        return ind + 1
    
    def bisect_right(self, x):
        return self.query_sum(x)

    def bisect_left(self, x):
        if x == 1:
            return 0
        return self.query_sum(x-1)

    
    def display(self):
        print('inside BIT:', end=' ')
        for x in range(1, self.max+1):
            if self.count(x):
                c = self.count(x)
                for _ in range(c):
                    print(x, end=' ')
        print()

import sys
input = sys.stdin.readline
from operator import itemgetter

INF = 10**15

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

for i in range(N):
    if i%2 == 1:
        a = A[i]
        A[i] = B[i]
        B[i] = a

INDs = []
def dfs(p,L):
    if p == N:
        if len(L) == (N+1)//2:
            INDs.append(L)
        return
    dfs(p+1, L+[p])
    dfs(p+1, L)
    return

dfs(0, [])

ans = INF
for IND in INDs:
    As = []
    Bs = []
    usingA = [False]*N
    for ind in IND:
        usingA[ind] = True
    for ind in range(N):
        if usingA[ind]:
            As.append((A[ind], ind))
        else:
            Bs.append((B[ind], ind))
    As.sort()
    Bs.sort()
    ok = True
    pre = -INF
    Array = [None]*N
    for i in range(N):
        if i%2 == 0:
            if As[i//2][0] < pre:
                ok = False
                break
            Array[As[i//2][1]] = i+1
            pre = As[i//2][0]
        else:
            if Bs[i//2][0] < pre:
                ok = False
                break
            Array[Bs[i//2][1]] = i+1
            pre = Bs[i//2][0]
    if not ok:
        continue
    
    bit = BITbisect(N)
    nowans = 0
    for j, a in enumerate(Array):
        nowans += j - bit.query_sum(a)
        bit.add(a, 1)
    
    if nowans < ans:
        ans = nowans

if ans == INF:
    print(-1)
else:
    print(ans)

Solution (Python):
import itertools
import math
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7



N = int(sys.stdin.buffer.readline())
A = list(map(int, sys.stdin.buffer.readline().split()))
B = list(map(int, sys.stdin.buffer.readline().split()))


class BinaryIndexedTree:
    
    def __init__(self, size):
        """
        :param int size:
        """
        self._bit = [0] * size
        self._size = size

    def add(self, i, w):
        """
        i 番目に w を加える
        :param int i:
        :param int w:
        """
        x = i + 1
        while x <= self._size:
            self._bit[x - 1] += w
            x += x & -x

    def sum(self, i):
        """
        [0, i) の合計
        :param int i:
        """
        ret = 0
        while i > 0:
            ret += self._bit[i - 1]
            i -= i & -i
        return ret

    def __len__(self):
        return self._size




ans = INF
for evens_i in itertools.combinations(range(N), r=(N + 1) // 2):
    is_even = [False] * N
    for i in evens_i:
        is_even[i] = True
    evens = []
    odds = []
    for i, even in enumerate(is_even):
        if even:
            evens.append((A[i] if i % 2 == 0 else B[i], i))
        else:
            odds.append((A[i] if i % 2 == 1 else B[i], i))
    evens.sort()
    odds.sort()

    prev = -1
    
    bit = BinaryIndexedTree(size=N)
    ok = True
    cnt = 0
    for i in range(N):
        c, mi = [evens, odds][i % 2][i // 2]
        if c < prev:
            ok = False
            break
        prev = c
        cnt += i - bit.sum(mi)
        bit.add(mi, 1)
    if ok:
        ans = min(ans, cnt)
        
if ans == INF:
    print(-1)
else:
    print(int(ans))

Solution (Python):
import itertools
class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
def invnum(n,a):
    bit=Bit(n)
    res=0
    for j in range(n):
        res+=j-bit.sum(a[j])
        bit.add(a[j],1)
N=int(input())
A=[int(i) for i in input().split()]
B=[int(i) for i in input().split()]
flag=0
M=-1
if N%2==0:
    M=N//2
else:
    M=N//2+1
ans=(N*(N-1))//2
for seq in itertools.combinations(range(N),M):
    X=[]
    Y=[]
    era=[0 for i in range(N)]
    for i in seq:
        if i%2==0:
            X.append((A[i],i))
        else:
            X.append((B[i],i))
        era[i]=1
    for i in range(N):
        if era[i]==0:
            if i%2==0:
                Y.append((B[i],i))
            else:
                Y.append((A[i],i))
    X.sort()
    Y.sort()
    L=[]
    if N%2==1:
        for i in range(M-1):
            L.append(X[i])
            L.append(Y[i])
        L.append(X[-1])
    else:
        for i in range(M):
            L.append(X[i])
            L.append(Y[i])
    
    flag2=1
    for i in range(N-1):
        if L[i][0]>L[i+1][0]:
            flag2=0
            break
    if flag2==1:
        flag=1
        S=[L[i][1] for i in range(N)]
        tmp=0
        for i in range(N):
            for j in range(i+1,N):
                if S[i]>S[j]:
                    tmp+=1
        ans=min(tmp,ans)
if flag==1:
    print(ans)
else:
    print(-1)

Solution (Python):
import sys
input = sys.stdin.readline

N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))

UP=(N+1)//2
DOWN=N-UP

ANS=1<<31

def ten(A):
    LEN=len(A)
    MAX=max(A)
    MIN=min(A)

    BIT=[0]*(MAX-MIN+2)

    def update(v,w):
        while v<=MAX-MIN+1:
            BIT[v]+=w
            v+=(v&(-v))

    def getvalue(v):
        ANS=0
        while v!=0:
            ANS+=BIT[v]
            v-=(v&(-v))
        return ANS

    ANS=0        
    for i in range(LEN):
        bit_ai=A[i]-MIN+1

        ANS+=i
        ANS-=getvalue(bit_ai)
        

        update(bit_ai,1)

    return ANS
    

for i in range(1<<N):
    UD=[0,0]
    S0=[]
    S1=[]

    for j in range(N):
        if (1<<j) & i !=0:
            if j%2==0:
                S0.append((A[j],j))
            else:
                S1.append((A[j],j))
            UD[j%2]+=1

        else:
            if (j+1)%2==0:
                S0.append((B[j],j))
            else:
                S1.append((B[j],j))
                
            UD[(j+1)%2]+=1

    if UD[0]==UP and UD[1]==DOWN:
        S0.sort()
        S1.sort()
        

        for i in range(1,N):
            if i%2==0:
                if S0[i//2][0]>=S1[(i-1)//2][0]:
                    True
                else:
                    break
            else:
                if S1[i//2][0]>=S0[(i-1)//2][0]:
                    True
                else:
                    break
        else:
            K=[]
            for i in range(N):
                if i%2==0:
                    K.append(S0[i//2][1])
                else:
                    K.append(S1[i//2][1])

            
            

            ANS=min(ANS,ten(K))

if ANS==1<<31:
    print(-1)
else:
    print(ANS)

Solution (Python):
n = int(input())
A = list(map(int,input().split()))
B = list(map(int,input().split()))

A = [A,B]

import itertools

C = list(itertools.combinations([i for i in range(n)], n//2))
D = [[0] * 2 for i in range(n)]


def sw(G):
    a = 0
    
    for i in range(len(G)):
        j = i
        while G[j] != i:
            j += 1
        for k in range(j, i, -1):
            ss = G[k]
            G[k] = G[k-1]
            G[k-1] = ss
            a += 1
            
    
    return a

ans = float("inf")

for i in range(len(C)):
    D = [[0] * 2 for i in range(n//2)]
    E = [[0] * 2 for i in range(n - n//2)]
    L = [0] * n
    for k in range(len(C[i])):
        D[k][0] = A[(C[i][k]+1)%2][C[i][k]]
        D[k][1] = C[i][k]
        L[C[i][k]] = 1
    l = 0
    for k in range(n):
        if L[k] == 0:
            E[l][0] = A[k%2][k]
            E[l][1] = k
            l += 1
    D.sort(key=lambda x:x[1])
    D.sort()
    E.sort(key=lambda x:x[1])
    E.sort()
    F = []
    for i in range(n):
        if i % 2 == 0:
            F.append(E[i//2])
        else:
            F.append(D[i//2])
    
    ok = 1
    for i in range(len(F)-1):
        if F[i][0] > F[i+1][0]:
            ok = 0
    
    if ok == 1:
        ans0 = sw([F[i][1] for i in range(n)])
        ans = min(ans, ans0)
    
if ans == float("inf"):
    ans = -1
print(ans)

Solution (Python):
class Rsum():
	def __init__(self, size):
		
		self.n = 1
		while self.n < size:
			self.n *= 2
		self.node = [0] * (2*self.n-1)

	def Access(self, x):
		return self.node[x+self.n-1]

	def Add(self, x, val):
		x += self.n-1
		self.node[x] += val
		while x > 0:
			x = (x-1)//2
			self.node[x] = self.node[2*x+1] + self.node[2*x+2]
		return

	
	def Get(self, l, r):
		L, R = l+self.n, r+self.n
		s = 0
		while L<R:
			if R & 1:
				R -= 1
				s += self.node[R-1]
			if L & 1:
				s += self.node[L-1]
				L += 1
			L >>= 1
			R >>= 1
		return s

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

ans = 200
for bit in range(1<<n):
	if sum(list(map(int, list(bin(bit)[2:])))) %2 == 1:
		continue
	if sum([(i%2) ^ ((bit>>i)&1) for i in range(n)]) != n//2:
		continue
	c = [[b[i], i, (i%2) ^ ((bit>>i)&1)] if (bit>>i)&1 == True else [a[i], i, (i%2) ^ ((bit>>i)&1)] for i in range(n)]
	
	even = 0
	odd = 1
	c.sort(key=lambda x: (x[0], x[1]))
	
	goal = [-1 for _ in range(n)]
	for i, p in enumerate(c):
		x, y, z = p
		if z == 0:
			goal[even] = [x, y]
			even += 2
		else:
			goal[odd] = [x, y]
			odd += 2
	
	ok = True
	for i in range(n-1):
		if goal[i][0] > goal[i+1][0]:
			ok = False
			break
	if not ok:
		continue

	tmp = 0
	st = Rsum(n)
	for x, y in goal:
		tmp += st.Get(y, n)
		st.Add(y, 1)
	ans = min(ans, tmp)

if ans == 200:
	print(-1)
else:
	print(ans)

Solution (Python):
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())


N = inp()
AA = inpl()
BB = inpl()






cards = []
for i,(a,b) in enumerate(zip(AA,BB)):
    if i%2 == 0:
        cards.append((a, b, i))
    else:
        cards.append((b, a, i))


n = (N+1)//2


def solve(ii):
    tmp = 0
    
    for _ in range(N):
        next = []
        for k, i in enumerate(ii):
            if i == 0:
                tmp += k
            else:
                next.append(i-1)
        ii = next[:]
    
    return tmp




ans = INF
for Acards in itertools.combinations(cards, n):
    Ais = sorted([(Acard[0], Acard[2]) for Acard in Acards])

    ii = set([i for A,i in Ais])
    Bis = []
    for a,b,i in cards:
        if i not in ii:
            Bis.append((b,i))
    Bis.sort()

    nums = []
    ii = []
    for i in range(N):
        if i%2 == 0:
            n,i = Ais[i//2]
        else:
            n,i = Bis[i//2]
        nums.append(n)
        ii.append(i)

    
    if nums != sorted(nums):
        continue
    else:
        ans = min(ans,solve(ii))


if ans == INF:
    print(-1)
else:
    print(ans)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
ans = 10**10
for bit in range(1<<n):
  l = a[:]
  rev = [0]*n
  for i in range(n):
    if bit & 1<<i:
      rev[i] = 1
      l[i] = b[i]
  if sum(rev) % 2:
    continue
  odd = list()
  even = list()
  for i in range(n):
    if rev[i]^(i&1):
      even.append((l[i],i))
    else:
      odd.append((l[i],i))
  if len(even) != n//2:
    continue
  odd.sort()
  even.sort()
  l = list()
  for x,y in zip(odd,even):
    l.append(x)
    l.append(y)
  if n&1: l.append(odd[-1])
  fl = 0
  for x,y in zip(l,l[1:]):
    if x[0] > y[0]:
      fl = 1
      break
  if fl: continue
  f = [x[1] for x in l]
  
  cnt = 0
  g = [0]*n
  for x in f:
    cnt += sum(g[x:])
    g[x] = 1
  if ans > cnt:
    ans = cnt
if ans > 10**9:
  ans = -1
print(ans)

Solution (Python):

def solve() : 
    n = int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    m = 1<<n
    dp = [[10000 for i in range(n)] for i in range(m)]
    for i in range(n) :
        dp[1<<i][i]=0
    for i in range(m) :
        c = 0
        for j in range(n) :
            if (1<<j)&i != 0 : c += 1
        cnt = c
        for j in range(n) :
            if (1<<j)&i == 0 : continue
            cnt -= 1
            pre = i - (1<<j)
            for k in range(n) :
                if (1<<k) & i == 0 : continue
                cur = (b[k] if (c-k)%2 == 1 else a[k])
                nxt = (a[j] if (c-j)%2 == 1 else b[j])
                if cur <= nxt : dp[i][j]=min(dp[i][j],dp[pre][k]+cnt)
    ans = 10000
    for i in range(n) :
        ans = min(ans,dp[m-1][i])
    print(ans if ans != 10000 else -1)
solve()