Keyence Programming Contest 2020 - Swap and Flip

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.

Examples

Input

3
3 4 3
3 2 3


Output

1


Input

2
2 1
1 2


Output

-1


Input

4
1 2 3 4
5 6 7 8


Output

0


Input

5
28 15 22 43 31
20 22 43 33 32


Output

-1


Input

5
4 46 6 38 43
33 15 18 27 37


Output

3

Source: atcoder | Difficulty: UNKNOWN_DIFFICULTY


Solutions:
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)


n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
dp = [[10 ** 9 for _ in range(51)] for __ in range(1 << n)]
dp[0][0] = 0
for i in range(1 << n):
	target = bin(i).count('1') - 1
	cnt = bin(i).count('1')
	for j in range(n):
		if i >> j & 1:
			cnt -= 1
			if abs(j - target) % 2 == 0:
				nxt = a[j]
			else:
				nxt = b[j]
			for k in range(nxt + 1):
				if dp[i ^ 1 << j][k] != 10 ** 9:
					dp[i][nxt] = min(dp[i][nxt], dp[i ^ 1 << j][k] + abs(j + cnt - target))
ans = min(dp[2 ** n - 1])
print(ans if ans < 10 ** 9 else -1)


import sys
input = sys.stdin.readline
n = int(input())
a = [int(item) for item in input().split()]
b = [int(item) for item in input().split()]
odd_bit = 1398101
eve_bit = 2796202
full_bit = 2 ** n - 1
odd_num = (n + 1) // 2
ans = 10 ** 9
for i in range(2 ** n):
	invi = full_bit ^ i
	odd = bin(i & odd_bit).count('1') + bin(invi & eve_bit).count('1')
	if odd != odd_num:
		continue
	odd_card = []
	eve_card = []
	for j in range(n):
		if i & 1 << j:
			if j % 2 == 0:
				odd_card.append((a[j], j))
			else:
				eve_card.append((a[j], j))
		elif j % 2 == 0:
			eve_card.append((b[j], j))
		else:
			odd_card.append((b[j], j))
	odd_card.sort()
	eve_card.sort()
	odd_itr = 0
	eve_itr = 0
	curr = 0
	val = 0
	ok = True
	perm = []
	for i in range(n):
		if i % 2 == 0:
			(num, index) = odd_card[odd_itr]
			perm.append(index)
			odd_itr += 1
		else:
			(num, index) = eve_card[eve_itr]
			perm.append(index)
			eve_itr += 1
		if num < curr:
			ok = False
			break
		curr = num
	if ok:
		val = 0
		visited = [0] * n
		itr = 0
		for item in perm:
			visited[item] = 1
			val += itr - sum(visited[:item])
			itr += 1
		ans = min(ans, val)
if ans == 10 ** 9:
	print(-1)
else:
	print(ans)


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)


printn = lambda x: print(x, end='')
inn = lambda : int(input())
inl = lambda : list(map(int, input().split()))
inm = lambda : map(int, input().split())
ins = lambda : input().strip()
DBG = True and False
BIG = 10 ** 18
R = 10 ** 9 + 7

def ddprint(x):
	if DBG:
		print(x)
import itertools
n = inn()
a = inl()
b = inl()
cms = itertools.combinations(list(range(n)), n // 2)
mn = BIG
for cm in cms:
	ev = []
	od = []
	for i in range(n):
		if i not in cm:
			ev.append((a[i] if i % 2 == 0 else b[i], i))
		else:
			od.append((a[i] if i % 2 == 1 else b[i], i))
	ev.sort()
	od.sort()
	p = []
	q = []
	for i in range(n):
		if i % 2 == 0:
			p.append(ev[i // 2][1])
			q.append(ev[i // 2][0])
		else:
			p.append(od[i // 2][1])
			q.append(od[i // 2][0])
	ok = True
	for i in range(n - 1):
		if q[i] > q[i + 1]:
			ok = False
			break
	if not ok:
		continue
	x = 0
	for i in range(n // 2):
		m = p.index(i)
		tmp = p[m]
		for j in range(m, i, -1):
			p[j] = p[j - 1]
		p[i] = tmp
		x += m - i
		m = p.index(n - 1 - i)
		tmp = p[m]
		for j in range(m, n - 1 - i):
			p[j] = p[j + 1]
		p[n - 1 - i] = tmp
		x += n - 1 - i - m
	mn = min(mn, x)
print(mn if mn < BIG else -1)


import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
from math import floor, ceil, sqrt, factorial, hypot, log
from heapq import heappop, heappush, heappushpop
from collections import Counter, defaultdict, deque
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from copy import deepcopy
inf = float('inf')
mod = 10 ** 9 + 7

def pprint(*A):
	for a in A:
		print(*a, sep='\n')

def INT_(n):
	return int(n) - 1

def MI():
	return map(int, input().split())

def MF():
	return map(float, input().split())

def MI_():
	return map(INT_, input().split())

def LI():
	return list(MI())

def LI_():
	return [int(x) - 1 for x in input().split()]

def LF():
	return list(MF())

def LIN(n: int):
	return [I() for _ in range(n)]

def LLIN(n: int):
	return [LI() for _ in range(n)]

def LLIN_(n: int):
	return [LI_() for _ in range(n)]

def LLI():
	return [list(map(int, l.split())) for l in input()]

def I():
	return int(input())

def F():
	return float(input())

def ST():
	return input().replace('\n', '')

class BinaryIndexedTree:

	def __init__(self, size):
		self.__node = [0] * (size + 1)
		self.size = size

	def add(self, index, value):
		while index <= self.size:
			self.__node[index] += value
			index += index & -index

	def sum(self, index):
		ret = 0
		while index > 0:
			ret += self.__node[index]
			index -= index & -index
		return ret

	def update_max(self, index, value):
		while index <= self.size:
			self.__node[index] = max(self.__node[index], value)
			index += index & -index

	def query_max(self, index):
		ret = 0
		while index > 0:
			ret = max(ret, self.__node[index])
			index -= index & -index
		return ret

	def get_node(self, index):
		return self.__node[index]

def Inversion_number(A):
	N = len(A)
	B = sorted(set(A))
	BIT = BinaryIndexedTree(N)
	res = 0
	for i in range(N):
		idx = bisect_left(B, A[i])
		inverse = i - BIT.sum(idx + 1)
		res += inverse
		BIT.add(idx + 1, 1)
	return res

def main():
	N = I()
	A = LI()
	B = LI()
	max_bit = 1 << N

	def check(mask):
		C = [0] * N
		for i in range(N):
			if mask >> i & 1:
				C[i] = B[i]
			else:
				C[i] = A[i]
		C.sort()
		dic = defaultdict(lambda : deque())
		for (j, c) in enumerate(C):
			dic[c, j & 1].append(j)
		indexes = [0] * N
		for i in range(N):
			if mask >> i & 1:
				(num, is_odd_idx) = (B[i], i & 1)
				if dic[num, is_odd_idx ^ 1]:
					idx = dic[num, is_odd_idx ^ 1].popleft()
				else:
					return inf
			else:
				(num, is_odd_idx) = (A[i], i & 1)
				if dic[num, is_odd_idx]:
					idx = dic[num, is_odd_idx].popleft()
				else:
					return inf
			indexes[i] = idx
		return Inversion_number(indexes)
	ans = inf
	for mask in range(max_bit):
		res = check(mask)
		if res < ans:
			ans = res
	if ans == inf:
		print(-1)
	else:
		print(ans)
main()


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)


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)


N = int(input())
(*A,) = map(int, input().split())
(*B,) = map(int, input().split())
INF = N * 100
ans = INF
for i in range(2 ** N):
	C = [(a, j, 0) if i >> j & 1 else (b, j, 1) for (j, a, b) in zip(range(N), A, B)]
	P = sum((p for (c, j, p) in C))
	if P % 2:
		continue
	E = sum((p for (c, j, p) in C[::2]))
	O = sum((p for (c, j, p) in C[1::2]))
	if E != O:
		continue
	C0 = []
	C1 = []
	for (c, j, p) in C:
		if (p + j) % 2:
			C1.append((c, j, p))
		else:
			C0.append((c, j, p))
	C0.sort()
	C1.sort()
	D = []
	E = []
	for (c0, c1) in zip(C0, C1):
		E.append(c0[0])
		E.append(c1[0])
		D.append(c0[1])
		D.append(c1[1])
	if N % 2:
		D.append(C0[-1][1])
		E.append(C0[-1][0])
	contFlg = False
	for (e, e2) in zip(E[:-1], E[1:]):
		if e > e2:
			contFlg = True
			break
	if contFlg:
		continue
	tmp = 0
	for (i, d) in enumerate(D):
		for (j, d2) in enumerate(D[:i]):
			if d2 > d:
				tmp += 1
	ans = min(ans, tmp)
if ans == INF:
	ans = -1
print(ans)


import sys
input = sys.stdin.buffer.readline
from collections import defaultdict
import itertools

class BIT:

	def __init__(self, N):
		self.size = N
		self.tree = [0] * (N + 1)

	def sum(self, t):
		s = 0
		while t > 0:
			s += self.tree[t]
			t -= t & -t
		return s

	def add(self, t, x):
		while t <= self.size:
			self.tree[t] += x
			t += t & -t

def getlist():
	return list(map(int, input().split()))

def main():
	N = int(input())
	A = getlist()
	B = getlist()
	omote = []
	ura = []
	for i in range(N):
		if i % 2 == 0:
			omote.append([A[i], i])
			ura.append([B[i], i])
		else:
			omote.append([B[i], i])
			ura.append([A[i], i])
	seq = [i for i in range(N)]
	alllist = list(itertools.combinations(seq, int((N + 1) // 2)))
	M = len(alllist)
	ans = float('inf')
	for i in range(M):
		lis = alllist[i]
		USE = [0] * N
		for j in lis:
			USE[j] = 1
		X = []
		Y = []
		for j in range(N):
			if USE[j] == 1:
				X.append(omote[j])
			else:
				Y.append(ura[j])
		X = sorted(X)
		Y = sorted(Y)
		sequence = []
		for j in range(N):
			if j % 2 == 0:
				sequence.append(X[int(j // 2)])
			else:
				sequence.append(Y[int(j // 2)])
		judge = 'Yes'
		for j in range(N - 1):
			if sequence[j][0] > sequence[j + 1][0]:
				judge = 'No'
				break
		if judge == 'Yes':
			bit = []
			for j in range(N):
				bit.append(sequence[j][1] + 1)
			val = 0
			calc = BIT(50)
			for j in range(N):
				calc.add(bit[j], 1)
				val += j + 1 - calc.sum(bit[j])
			ans = min(ans, val)
	if ans == float('inf'):
		print(-1)
	else:
		print(ans)
main()


import sys
from collections import defaultdict
INF = float('inf')

def bit_sum(n):
	return bin(n).count('1')

def solve(N: int, A: 'List[int]', B: 'List[int]'):
	DP = [[INF] * 51 for _ in range(1 << N)]
	DP[0][0] = 0
	for bit in range(1 << N):
		ketawa = bit_sum(bit)
		rest = []
		counter = ketawa
		for i in range(N):
			if bit & 1 << i:
				continue
			rest.append((i, counter))
			counter += 1
		for s in range(51):
			if DP[bit][s] == INF:
				continue
			for (orig, curr) in rest:
				if (orig - ketawa) % 2 == 0:
					front = A[orig]
				else:
					front = B[orig]
				if front >= s:
					DP[bit | 1 << orig][front] = min(DP[bit | 1 << orig][front], DP[bit][s] + abs(curr - ketawa))
	ans = min(DP[-1])
	if ans == INF:
		print(-1)
	else:
		print(ans)

def main():

	def iterate_tokens():
		for line in sys.stdin:
			for word in line.split():
				yield word
	tokens = iterate_tokens()
	N = int(next(tokens))
	A = [int(next(tokens)) for _ in range(N)]
	B = [int(next(tokens)) for _ in range(N)]
	solve(N, A, B)
main()


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)


class BinaryIndexedTree:

	def __init__(self, n):
		self.n = n
		self.tree = [0 for _ in range(n + 1)]

	def sum(self, index):
		res = 0
		while index:
			res += self.tree[index]
			index -= index & -index
		return res

	def add(self, index, x):
		while index <= self.n:
			self.tree[index] += x
			index += index & -index

	def bisect_left(self, x):
		if x <= 0:
			return 0
		(res, tmp) = (0, 2 ** (self.n.bit_length() - 1))
		while tmp:
			if res + tmp <= self.n and self.tree[res + tmp] < x:
				x -= self.tree[res + tmp]
				res += tmp
			tmp >>= 1
		return res + 1
INF = 10 ** 18
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
res = INF
for i in range(2 ** N):
	front = []
	back = []
	for j in range(N):
		if i >> j & 1:
			front.append((A[j], j))
		else:
			back.append((B[j], j))
	odd = []
	even = []
	for (x, j) in front:
		if j % 2 == 0:
			odd.append((x, j))
		else:
			even.append((x, j))
	for (x, j) in back:
		if j % 2 != 0:
			odd.append((x, j))
		else:
			even.append((x, j))
	if len(even) != N // 2:
		continue
	odd.sort()
	even.sort()
	seq = []
	for j in range(N):
		if j % 2 == 0:
			seq.append(odd[j // 2])
		else:
			seq.append(even[j // 2])
	for j in range(N - 1):
		if seq[j][0] > seq[j + 1][0]:
			break
	else:
		bit = BinaryIndexedTree(N)
		count = 0
		for j in range(N):
			bit.add(seq[j][1] + 1, 1)
			count += j + 1 - bit.sum(seq[j][1] + 1)
		res = min(res, count)
print(res if res != INF else -1)


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):
		self._bit = [0] * size
		self._size = size

	def add(self, i, w):
		x = i + 1
		while x <= self._size:
			self._bit[x - 1] += w
			x += x & -x

	def sum(self, 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))


import sys
import itertools
INF = float('INF')
N = int(input())
AA = list(map(int, sys.stdin.readline().split()))
BB = list(map(int, sys.stdin.readline().split()))
cards = set()
for (i, (a, b)) in enumerate(zip(AA, BB)):
	if i % 2 == 0:
		cards.add((a, b, i))
	else:
		cards.add((b, a, i))

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 + 1) // 2):
	Bcards = cards - set(Acards)
	Ais = sorted([(card[0], card[2]) for card in Acards])
	Bis = sorted([(card[1], card[2]) for card in Bcards])
	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 == 0:
			print(0)
			sys.exit()
if ans == INF:
	print(-1)
else:
	print(ans)


N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
AB = sorted(list(set(A + B)))
D = {ab: i + 1 for (i, ab) in enumerate(AB)}
A = [D[a] for a in A]
B = [D[a] for a in B]
ans = 1 << 100
for m in range(1 << N):
	b = bin(m)
	if b[::2].count('1') != b[1::2].count('1'):
		continue
	C = [[], []]
	for i in range(N):
		p = m >> i & 1
		q = p + i & 1
		C[q].append(((A[i] if p == 0 else B[i]) << 5) + i)
	if len(C[1]) != N // 2:
		continue
	C[0].sort()
	C[1].sort()
	CC = [C[i & 1][i // 2] for i in range(N)]
	for i in range(1, N):
		if CC[i - 1] >> 5 > CC[i] >> 5:
			break
	else:
		CCC = [c % 32 for c in CC]
		t = 0
		for i in range(N):
			for j in range(i):
				if CCC[i] < CCC[j]:
					t += 1
		ans = min(ans, t)
print(ans if ans < 1 << 100 else -1)


import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub
sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2 ** 62 - 1

def read_int():
	return int(input())

def read_int_n():
	return list(map(int, input().split()))

def read_float():
	return float(input())

def read_float_n():
	return list(map(float, input().split()))

def read_str():
	return input().strip()

def read_str_n():
	return list(map(str, input().split()))

def error_print(*args):
	print(*args, file=sys.stderr)

def mt(f):
	import time

	def wrap(*args, **kwargs):
		s = time.time()
		ret = f(*args, **kwargs)
		e = time.time()
		error_print(e - s, 'sec')
		return ret
	return wrap

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

@mt
def slv(N, A, B):
	AB = list(zip(A, B))
	ans = INF
	for f in product(range(2), repeat=N):
		o = []
		e = []
		for (i, (c, ab)) in enumerate(zip(f, AB)):
			v = ab[c]
			if i % 2 == 0:
				if c == 0:
					e.append((v, i))
				else:
					o.append((v, i))
			elif f[i] == 0:
				o.append((v, i))
			else:
				e.append((v, i))
		if 0 <= len(e) - len(o) <= 1:
			bit = Bit(50)
			e.sort()
			o.sort()
			eo = [e, o]
			cand = 0
			p = -1
			for i in range(N):
				if p > eo[i % 2][i // 2][0]:
					break
				p = eo[i % 2][i // 2][0]
				bit.add(eo[i % 2][i // 2][1] + 1, 1)
				cand += i + 1 - bit.sum(eo[i % 2][i // 2][1] + 1)
			else:
				ans = min(ans, cand)
	if ans == INF:
		ans = -1
	return ans

def main():
	N = read_int()
	A = read_int_n()
	B = read_int_n()
	print(slv(N, A, B))
main()


n = int(input())
a = [list(map(int, input().split())) for _ in range(2)]
dp = [[1000] * 2 ** n for _ in range(51)]
dp[0][0] = 0
for S in range(2 ** n):
	j = bin(S).count('1')
	cnt = 0
	for i in range(n):
		if not S & 1 << i:
			k = a[(i + j) % 2][i]
			for l in range(k + 1):
				dp[k][S | 1 << i] = min(dp[k][S | 1 << i], dp[l][S] + cnt)
		if not S & 1 << i:
			cnt += 1
ans = min((dp[i][-1] for i in range(51)))
if ans == 1000:
	print(-1)
else:
	print(ans)


N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
AB = sorted(list(set(A + B)))
D = {ab: i + 1 for (i, ab) in enumerate(AB)}
A = [D[a] for a in A]
B = [D[a] for a in B]

def chk(L):
	NN = 5
	BIT = [0] * (2 ** NN + 1)

	def addbit(i):
		while i <= 2 ** NN:
			BIT[i] += 1
			i += i & -i

	def getsum(i):
		ret = 0
		while i != 0:
			ret += BIT[i]
			i -= i & -i
		return ret
	s = 0
	for l in L[::-1]:
		s += getsum(l + 1)
		addbit(l + 1)
	return s
ans = 1 << 100
for m in range(1 << N):
	if bin(m).count('1') & 1:
		continue
	C = [[], []]
	for i in range(N):
		p = m >> i & 1
		q = p + i & 1
		C[q].append(((A[i] if p == 0 else B[i]) << 5) + i)
	if len(C[1]) != N // 2:
		continue
	C[0].sort()
	C[1].sort()
	CC = [C[i & 1][i // 2] for i in range(N)]
	for i in range(1, N):
		if CC[i - 1] >> 5 > CC[i] >> 5:
			break
	else:
		CCC = [c % 32 for c in CC]
		ans = min(ans, chk(CCC))
print(ans if ans < 1 << 100 else -1)


import sys
from itertools import accumulate

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def pop_count(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	i = i + (i >> 4) & 252645135
	i = i + (i >> 8)
	i = i + (i >> 16)
	return i & 63
N = INT()
cards = [[]] * 2
cards[0] = LIST()
cards[1] = LIST()
dp = list2d(1 << N, N, INF)
for i in range(N):
	dp[1 << i][i] = 0
for S in range(1, 1 << N):
	popcnt = pop_count(S)
	acc = [0] * N
	for i in range(N):
		if S & 1 << i:
			acc[i] = 1
	acc = list(accumulate(acc[::-1]))[::-1]
	for i in range(N):
		if dp[S][i] == INF or not S & 1 << i:
			continue
		cur = cards[i & 1 ^ 1 - (popcnt & 1)][i]
		for j in range(N):
			if S & 1 << j:
				continue
			nxt = cards[j & 1 ^ popcnt & 1][j]
			if cur <= nxt:
				dp[S | 1 << j][j] = min(dp[S | 1 << j][j], dp[S][i] + acc[j])
ans = INF
for i in range(N):
	ans = min(ans, dp[(1 << N) - 1][i])
if ans == INF:
	print(-1)
else:
	print(ans)


def examA():
	H = I()
	W = I()
	N = I()
	ans = (N - 1) // max(H, W) + 1
	print(ans)
	return

def examB():
	N = I()
	XL = [LI() for _ in range(N)]
	for i in range(N):
		XL[i][0] += XL[i][1]
	XL.sort()
	ans = 0
	now = -inf
	for i in range(N):
		if XL[i][0] - XL[i][1] * 2 >= now:
			ans += 1
			now = XL[i][0]
	print(ans)
	return

def examC():
	(N, K, S) = LI()
	A = [0] * N
	if S >= 10 ** 6:
		a = 1
	else:
		a = S + 1
	for i in range(N):
		if i < K:
			A[i] = S
		else:
			A[i] = a
	print(' '.join(map(str, A)))
	return

def examD():
	N = I()
	A = LI()
	B = LI()
	loop = 2 ** N
	ans = inf
	for i in range(loop):
		cur = 0
		nowA = []
		l = -1
		r = 0
		for j in range(N):
			if i & 1 << j == 1 << j:
				cur += 1
				nowA.append(B[j])
				if l == -1:
					l = j
				r = j + 1
			else:
				nowA.append(A[j])
		if cur % 2 == 1:
			continue
		if l == -1:
			l = 0
		pr = sorted(nowA)
		now = 0
		for j in range(N):
			dist = [i for (i, x) in enumerate(pr) if x == nowA[j]]
			candi = inf
			for v in dist:
				if abs(v - j) % 2 == 1 and i & 1 << j == 1 << j:
					candi = min(candi, abs(v - j))
				if abs(v - j) % 2 == 0 and i & 1 << j == 0:
					candi = min(candi, abs(v - j))
			if candi == inf:
				now = inf
				break
			else:
				if candi == 0 and l <= j < r:
					candi = 2
				now += candi
		ans = min(ans, now)
	if ans == inf:
		print(-1)
	else:
		print(ans // 2)
	return

def examD2():

	class Bit:

		def __init__(self, n):
			self.size = n
			self.tree = [0] * (n + 1)
			return

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

		def add(self, i, x=1):
			while i <= self.size:
				self.tree[i] += x
				i += i & -i
			return

		def search(self, x):
			i = 0
			s = 0
			step = 1 << self.size.bit_length() - 1
			while step:
				if i + step <= self.size and s + self.tree[i + step] < x:
					i += step
					s += self.tree[i]
				step >>= 1
			return i + 1

		def debug(self, k):
			return [self.sum(i) for i in range(k)]

		def inversion(self, A=[3, 10, 1, 8, 5]):
			res = 0
			for (i, p) in enumerate(A):
				self.add(p, 1)
				res += i + 1 - self.sum(p)
			return res
	N = I()
	A = LI()
	B = LI()
	ans = inf
	loop = 1 << N
	for l in range(loop):
		LO = []
		LE = []
		for j in range(N):
			if l & 1 << j > 0:
				if j % 2 == 0:
					LE.append((B[j], j + 1))
				else:
					LO.append((B[j], j + 1))
			elif j % 2 == 0:
				LO.append((A[j], j + 1))
			else:
				LE.append((A[j], j + 1))
		if len(LO) - len(LE) != N % 2:
			continue
		LO.sort()
		LE.sort()
		L = []
		L.append(LO[0][1])
		flag = True
		for i in range(1, N):
			if i % 2 == 1:
				if LE[i // 2][0] >= LO[i // 2][0]:
					L.append(LE[i // 2][1])
				else:
					flag = False
					break
			elif LO[i // 2][0] >= LE[i // 2 - 1][0]:
				L.append(LO[i // 2][1])
			else:
				flag = False
				break
		if flag:
			bit = Bit(51)
			now = bit.inversion(L)
			if ans > now:
				ans = now
	if ans == inf:
		ans = -1
	print(ans)
	return

def examD3():
	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
				elif 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)
	return

def examE():
	return
from copy import deepcopy
import sys, copy, bisect, itertools, heapq, math
from heapq import heappop, heappush, heapify
from collections import Counter, defaultdict, deque

def I():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LSI():
	return list(map(str, sys.stdin.readline().split()))

def LS():
	return sys.stdin.readline().split()

def SI():
	return sys.stdin.readline().strip()
global mod, mod2, inf, alphabet
mod = 10 ** 9 + 7
mod2 = 998244353
inf = 10 ** 18
alphabet = [chr(ord('a') + i) for i in range(26)]
examD2()


from itertools import combinations

def solve():
	INF = 10 ** 5

	def getNumInversion(odrAs):

		def makeBIT(numEle):
			numPow2 = 2 ** (numEle - 1).bit_length()
			data = [0] * (numPow2 + 1)
			return (data, numPow2)

		def addValue(iA, A):
			iB = iA + 1
			while iB <= numPow2:
				data[iB] += A
				iB += iB & -iB

		def getSum(iA):
			iB = iA + 1
			ans = 0
			while iB > 0:
				ans += data[iB]
				iB -= iB & -iB
			return ans
		lenA = len(odrAs)
		(data, numPow2) = makeBIT(lenA)
		ans = 0
		for odrA in reversed(odrAs):
			ans += getSum(odrA)
			addValue(odrA, 1)
		return ans
	N = int(input())
	As = list(map(int, input().split()))
	Bs = list(map(int, input().split()))
	ans = INF
	for iEvens in combinations(range(N), r=N // 2):
		iEvens = set(iEvens)
		(COdds, CEvens) = ([], [])
		for i in range(N):
			if i in iEvens:
				if i % 2:
					CEvens.append((As[i], i))
				else:
					CEvens.append((Bs[i], i))
			elif i % 2:
				COdds.append((Bs[i], i))
			else:
				COdds.append((As[i], i))
		COdds.sort()
		CEvens.sort()
		Cs = []
		for (COdd, CEven) in zip(COdds, CEvens):
			Cs += [COdd, CEven]
		if N % 2:
			Cs += [COdds[-1]]
		for i in range(N - 1):
			if Cs[i][0] > Cs[i + 1][0]:
				break
		else:
			odrAs = [i for (C, i) in Cs]
			num = getNumInversion(odrAs)
			ans = min(ans, num)
			if ans == 0:
				break
	if ans == INF:
		print(-1)
	else:
		print(ans)
solve()


from itertools import combinations
import sys
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a2 = list()
b2 = list()
if n == 1:
	print(0)
	sys.exit()
for i in range(n):
	if i % 2:
		b2.append(a[i])
		a2.append(b[i])
	else:
		a2.append(a[i])
		b2.append(b[i])
ans = 10 ** 9
for idx in combinations(range(0, n), (n + 1) // 2):
	a3 = list()
	b3 = list()
	flag = True
	for i in range(n):
		if i in idx:
			a3.append([a2[i], i])
		else:
			b3.append([b2[i], i])
	a3.sort(key=lambda x: x[0])
	b3.sort(key=lambda x: x[0])
	for i in range(len(b3) - 1):
		if a3[i][0] > b3[i][0] or a3[i + 1][0] < b3[i][0]:
			flag = False
	if len(a3) > len(b3):
		if a3[-1][0] < b3[-1][0] or a3[-2][0] > b3[-1][0]:
			flag = False
	elif a3[-1][0] > b3[-1][0]:
		flag = False
	if flag:
		ansidx = list()
		for i in range(len(b3)):
			ansidx.append(a3[i][1])
			ansidx.append(b3[i][1])
		if len(a3) > len(b3):
			ansidx.append(a3[-1][1])
		swap = 0
		for i in range(n):
			for j in range(i, n):
				if ansidx[i] > ansidx[j]:
					swap += 1
		ans = min(ans, swap)
if ans == 10 ** 9:
	print('-1')
else:
	print(ans)


n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
ans = 10 ** 18
for i in range(1 << n):
	c = []
	for j in range(n):
		if i >> j & 1 == 0:
			c.append(a[j])
		else:
			c.append(b[j])
	d = sorted(c)
	ind = {}
	for (j, k) in enumerate(d):
		if (j % 2, k) not in ind:
			ind[j % 2, k] = j
	e = []
	ok = True
	for (j, k) in enumerate(c):
		j = ((i >> j & 1) + j) % 2
		if (j, k) not in ind:
			ok = False
			break
		l = ind[j, k]
		if l >= n or d[l] != k:
			ok = False
			break
		e.append(l)
		ind[j, k] += 2
	if ok:
		count = 0
		for k in range(n):
			for j in range(n - 1 - k):
				if e[j] > e[j + 1]:
					count += 1
					(e[j], e[j + 1]) = (e[j + 1], e[j])
		ans = min(ans, count)
if ans == 10 ** 18:
	print(-1)
else:
	print(ans)


import sys
import math
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)

def input():
	return sys.stdin.readline()[:-1]
mod = 10 ** 9 + 7

def I():
	return int(input())

def II():
	return map(int, input().split())

def III():
	return list(map(int, input().split()))

def Line(N, num):
	if N <= 0:
		return [[] for _ in range(num)]
	elif num == 1:
		return [I() for _ in range(N)]
	else:
		read_all = [tuple(II()) for _ in range(N)]
		return map(list, zip(*read_all))
from operator import itemgetter

def index_sort(A):
	return sorted(enumerate(A), key=itemgetter(1))
ceil = math.ceil
floor = math.floor
N = I()
A = III()
B = III()
ans = float('inf')
for i in range(1 << N):
	bits = format(i, 'b').zfill(N)
	last_odd_val = []
	last_even_val = []
	for (j, b) in enumerate(bits):
		if j % 2 == 0:
			if b == '0':
				last_even_val.append([A[j], j])
			else:
				last_odd_val.append([B[j], j])
		elif b == '0':
			last_odd_val.append([A[j], j])
		else:
			last_even_val.append([B[j], j])
	if len(last_even_val) != ceil(N / 2):
		continue
	s_odd = sorted(last_odd_val, key=lambda x: (x[0], x[1]))
	s_even = sorted(last_even_val, key=lambda x: (x[0], x[1]))
	flag = False
	eps = 10 ** (-2)
	for j in range(N // 2):
		if floor(s_even[j][0]) > floor(s_odd[j][0]):
			flag = True
			break
		if floor(s_even[j][0]) == floor(s_odd[j][0]):
			s_odd[j][0] = s_even[j][0] + eps
		if len(s_even) > j + 1:
			if floor(s_odd[j][0]) > floor(s_even[j + 1][0]):
				flag = True
				break
			if floor(s_odd[j][0]) == floor(s_even[j + 1][0]):
				s_even[j + 1][0] = s_odd[j][0] + eps
	if flag:
		continue
	val = [0.0] * N
	for s in s_even:
		val[s[1]] = s[0]
	for s in s_odd:
		val[s[1]] = s[0]
	count = 0
	for i in range(N):
		for j in range(i + 1, N):
			if val[i] > val[j]:
				count += 1
	if count < ans:
		ans = count
if ans == float('inf'):
	ans = -1
print(ans)


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = float('inf')
for ii in range(2 ** N):
	s = format(ii, 'b').zfill(N)
	on = 0
	for j in s:
		if j == '1':
			on += 1
	if on != (N + 1) // 2:
		continue
	q = []
	q2 = []
	for i in range(N):
		if s[i] == '1':
			if i % 2 == 0:
				q.append([A[i], i])
			else:
				q.append([B[i], i])
		elif i % 2 != 0:
			q2.append([A[i], i])
		else:
			q2.append([B[i], i])
	q.sort()
	q2.sort()
	q2.append([float('inf'), 0])
	flag = True
	nmax = 0
	for i in range((N + 1) // 2):
		if nmax > q[i][0]:
			flag = False
		nmax = q[i][0]
		if nmax > q2[i][0]:
			flag = False
		nmax = q2[i][0]
	if flag:
		r = []
		for i in range((N + 1) // 2):
			r.append(q[i][1])
			r.append(q2[i][1])
		now = 0
		z = [i for i in range(N)]
		for i in range(N):
			for j in range(len(z)):
				if z[j] == r[i]:
					now += j
					del z[j]
					break
		ans = min(now, ans)
if ans == float('inf'):
	ans = -1
print(ans)


from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
import pprint
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 13

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def I():
	return int(sys.stdin.buffer.readline())

def LS():
	return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()

def S():
	return sys.stdin.buffer.readline().rstrip().decode('utf-8')

def IR(n):
	return [I() for i in range(n)]

def LIR(n):
	return [LI() for i in range(n)]

def SR(n):
	return [S() for i in range(n)]

def LSR(n):
	return [LS() for i in range(n)]

def SRL(n):
	return [list(S()) for i in range(n)]

def MSRL(n):
	return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007

class BIT:

	def __init__(self, size):
		self.bit = [0] * size
		self.size = size
		self.total = 0

	def add(self, i, w):
		x = i + 1
		self.total += w
		while x <= self.size:
			self.bit[x - 1] += w
			x += x & -x
		return

	def sum(self, i):
		res = 0
		x = i + 1
		while x:
			res += self.bit[x - 1]
			x -= x & -x
		return res

def inv_cnt(seq):
	n = len(seq)
	bit = BIT(n)
	cnt = 0
	for i in range(n - 1, -1, -1):
		cnt += bit.sum(seq[i] - 1)
		bit.add(seq[i], 1)
	return cnt
n = I()
A = LI()
B = LI()
ans = INF
for odd_ind in combinations(range(n), n // 2):
	even_ind = set(range(n)) - set(odd_ind)
	odd_list = []
	even_list = []
	whole_num_list = []
	whole_idx_list = []
	for i in odd_ind:
		if i % 2:
			odd_list += [(A[i], i)]
		else:
			odd_list += [(B[i], i)]
	for j in even_ind:
		if j % 2:
			even_list += [(B[j], j)]
		else:
			even_list += [(A[j], j)]
	even_list.sort(reverse=1)
	odd_list.sort(reverse=1)
	while even_list or odd_list:
		(x, idx) = even_list.pop()
		whole_num_list += [x]
		whole_idx_list += [idx]
		if odd_list:
			(x, idx) = odd_list.pop()
			whole_num_list += [x]
			whole_idx_list += [idx]
	if whole_num_list == sorted(whole_num_list):
		ans = min(ans, inv_cnt(whole_idx_list))
if ans == INF:
	print(-1)
else:
	print(ans)


def main():
	N = int(input())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	M = max(max(A), max(B)) + 1
	INF = float('inf')
	dp = [[INF for _ in range(M)] for _ in range(1 << N)]
	dp[0][0] = 0
	for i in range(1 << N):
		idx = 0
		for k in range(N):
			if i >> k & 1 == 1:
				idx += 1
		for j in range(M):
			if dp[i][j] >= INF:
				continue
			for k in range(N):
				if i & 1 << k == 1:
					continue
				if abs(k - idx) % 2 == 0:
					c = A[k]
				else:
					c = B[k]
				if j > c:
					continue
				t = 0
				for l in range(k):
					if i >> l & 1 == 0:
						t += 1
				dp[i | 1 << k][c] = min(dp[i | 1 << k][c], dp[i][j] + t)
	ans = INF
	for i in range(M):
		ans = min(dp[(1 << N) - 1][i], ans)
	print(ans if ans < INF else -1)
main()


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
INF = 1 << 29
dp = [[INF] * 55 for _ in range((1 << N) + 1)]
dp[0][0] = 0
for bit in range(1 << N):
	con = 0
	for i in range(N):
		if bit & 1 << i:
			con += 1
	ords = []
	iters = con
	for i in range(N):
		if not bit & 1 << i:
			ords.append([i, iters])
			iters += 1
	for s in range(51):
		if dp[bit][s] >= INF:
			continue
		for p in ords:
			ns = -1
			if abs(p[0] - con) % 2 == 0:
				ns = A[p[0]]
			else:
				ns = B[p[0]]
			if ns >= s:
				dp[bit | 1 << p[0]][ns] = min(dp[bit | 1 << p[0]][ns], dp[bit][s] + abs(p[1] - con))
ans = INF
for s in range(51):
	ans = min(ans, dp[(1 << N) - 1][s])
if ans < INF:
	print(ans)
else:
	print(-1)


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
		elif cnt % 2 == 0:
			if even != odd + 1:
				break
		elif 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)


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
INF = 1 << 19
dp = [[INF for _ in range(50 + 1)] for _ in range(1 << N)]
dp[0][0] = 0
for bit in range(1 << N):
	num_used = bin(bit).count('1')
	idx = num_used
	remaining = []
	for i in range(N):
		if not bit & 1 << i:
			remaining.append((i, idx))
			idx += 1
	for s in range(51):
		if dp[bit][s] >= INF:
			continue
		for (ini, curr) in remaining:
			num = A[ini] if abs(ini - num_used) % 2 == 0 else B[ini]
			if num >= s:
				dp[bit | 1 << ini][num] = min(dp[bit | 1 << ini][num], dp[bit][s] + abs(num_used - curr))
ans = min((dp[-1][s] for s in range(51)))
print(ans if ans < INF else -1)


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
INF = N ** 3
max_ab = max(max(A), max(B)) + 1
dp = [[INF] * max_ab for _ in range(2 ** N)]
dp[0][0] = 0
for i in range(2 ** N):
	done = 0
	for j in range(N):
		if i >> j & 1:
			done += 1
	for right_end in range(max_ab):
		if dp[i][right_end] == INF:
			continue
		for add_last in range(N):
			if i >> add_last & 1:
				continue
			if abs(add_last - done) % 2 == 0:
				add_last_surface = A[add_last]
			else:
				add_last_surface = B[add_last]
			if right_end > add_last_surface:
				continue
			num = 0
			for k in range(add_last):
				if i >> k & 1 == 0:
					num += 1
			dp[i | 1 << add_last][add_last_surface] = min(dp[i | 1 << add_last][add_last_surface], dp[i][right_end] + num)
ans = min(dp[-1])
if ans == INF:
	print(-1)
else:
	print(ans)


import sys
from itertools import combinations
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

class BitSum:

	def __init__(self, n):
		self.n = n + 3
		self.table = [0] * (self.n + 1)

	def add(self, i, x):
		i += 1
		while i <= self.n:
			self.table[i] += x
			i += i & -i

	def sum(self, i):
		i += 1
		res = 0
		while i > 0:
			res += self.table[i]
			i -= i & -i
		return res

def main():

	def ng():
		px = -1
		for i in range(n):
			if i % 2:
				x = xx1[i // 2][1]
			else:
				x = xx0[i // 2][0]
			if x < px:
				return True
			px = x
		return False

	def change(ans):
		res = 0
		bit = BitSum(n)
		for (i, k) in enumerate(kk):
			res += i - bit.sum(k)
			if res > ans:
				return ans
			bit.add(k, 1)
		return res
	n = II()
	aa = LI()
	bb = LI()
	ab = []
	for (i, (a, b)) in enumerate(zip(aa, bb)):
		if i % 2:
			ab.append([b, a, i])
		else:
			ab.append([a, b, i])
	ans = 1000
	for odd in combinations(range(n), n // 2):
		isodd = [False] * n
		xx0 = []
		xx1 = []
		for i in odd:
			xx1.append(ab[i])
			isodd[i] = True
		for i in range(n):
			if isodd[i]:
				continue
			xx0.append(ab[i])
		xx0.sort(key=lambda x: (x[0], x[2]))
		xx1.sort(key=lambda x: (x[1], x[2]))
		if ng():
			continue
		kk = []
		for ([_, _, i0], [_, _, i1]) in zip(xx0, xx1):
			kk += [i0, i1]
		if n % 2:
			kk += [xx0[-1][2]]
		ans = change(ans)
	if ans == 1000:
		print(-1)
	else:
		print(ans)
main()


def main():
	import sys
	from itertools import combinations
	from operator import itemgetter
	input = sys.stdin.readline
	N = int(input())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	even = []
	odd = []
	for i in range(N):
		if i % 2:
			odd.append(A[i])
			even.append(B[i])
		else:
			even.append(A[i])
			odd.append(B[i])
	L = list(range(N))
	ans = 10 ** 9
	for v in combinations(L, N // 2):
		ok = 1
		tmp = []
		tmp_odd = []
		tmp_even = []
		for i in range(N):
			if i in v:
				tmp.append(odd[i] * 100)
				tmp_odd.append((odd[i], i))
			else:
				tmp.append(even[i] * 100)
				tmp_even.append((even[i], i))
		tmp_odd.sort(key=itemgetter(0))
		tmp_even.sort(key=itemgetter(0))
		tmp_check = []
		p = [0] * N
		for i in range(N):
			if i % 2:
				tmp_check.append(tmp_odd[i // 2][0])
				p[tmp_odd[i // 2][1]] = i
			else:
				tmp_check.append(tmp_even[i // 2][0])
				p[tmp_even[i // 2][1]] = i
		for i in range(N - 1):
			if tmp_check[i] > tmp_check[i + 1]:
				ok = 0
				break
		if not ok:
			continue
		for i in range(N):
			tmp[i] += p[i]
		ans_new = 0
		for i in range(N):
			for j in range(i + 1, N):
				if tmp[i] > tmp[j]:
					ans_new += 1
		ans = min(ans, ans_new)
	if ans == 10 ** 9:
		print(-1)
	else:
		print(ans)
main()


from itertools import combinations
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

def inversion(inds):
	bit = [0] * (N + 1)

	def bit_add(x, w):
		while x <= N:
			bit[x] += w
			x += x & -x

	def bit_sum(x):
		ret = 0
		while x > 0:
			ret += bit[x]
			x -= x & -x
		return ret
	inv = 0
	for ind in reversed(inds):
		inv += bit_sum(ind + 1)
		bit_add(ind + 1, 1)
	return inv
INF = float('inf')
ans = INF
for odd_idxs in combinations(range(N), N // 2):
	odd_idxset = set(odd_idxs)
	odds = []
	evens = []
	for i in range(N):
		if i in odd_idxset:
			odds.append((A[i] if i % 2 else B[i], i))
		else:
			evens.append((B[i] if i % 2 else A[i], i))
	odds.sort()
	evens.sort()
	vals = []
	inds = []
	for ((e, ei), (o, oi)) in zip(evens, odds):
		vals.append(e)
		vals.append(o)
		inds.append(ei)
		inds.append(oi)
	if len(evens) > len(odds):
		(v, i) = evens[-1]
		vals.append(v)
		inds.append(i)
	if any((a > b for (a, b) in zip(vals, vals[1:]))):
		continue
	ans = min(ans, inversion(inds))
print(-1 if ans == INF else ans)


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)


from itertools import permutations, combinations, chain
from collections import defaultdict
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

def dpinit(ps, val=0):
	import copy
	res = [val for i in [0] * ps[-1]]
	for i in ps[:-1][::-1]:
		res = [copy.deepcopy(res) for k in [0] * i]
	return res
inf = 10 ** 10
dp = [defaultdict(lambda : inf) for i in range(2 ** N + 1)]
dp[0][0] = 0
for b in range(2 ** N):
	c = bin(b).count('1')
	for i in range(1, N + 1):
		p = N - i
		f = 1 << p
		if b & f:
			continue
		nb = b | f
		k = bin(b % f).count('1')
		v = A[i - 1] if (i - c) % 2 == 1 else B[i - 1]
		for (val, inv) in dp[b].items():
			if val <= v:
				dp[nb][v] = min(dp[nb][v], inv + abs(c + 1 - (i + k)))
if not dp[2 ** N - 1]:
	print(-1)
	exit()
ans = min(dp[2 ** N - 1].values())
print(ans if ans != inf else -1)


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def pop_count(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	i = i + (i >> 4) & 252645135
	i = i + (i >> 8)
	i = i + (i >> 16)
	return i & 63
N = INT()
cards = [[]] * 2
cards[0] = LIST()
cards[1] = LIST()
ans = INF
for S in range(1 << N):
	if pop_count(S) % 2 != 0:
		continue
	A1 = [[] for i in range(2)]
	for i in range(N):
		if S & 1 << i:
			A1[i % 2 ^ 1].append((cards[1][i], i))
		else:
			A1[i % 2].append((cards[0][i], i))
	if len(A1[0]) != ceil(N, 2) or len(A1[1]) != N // 2:
		continue
	A1[0].sort(reverse=1)
	A1[1].sort(reverse=1)
	cnt = 0
	A2 = [0] * N
	idxs = [0] * N
	for i in range(N):
		(A2[i], idxs[i]) = A1[i % 2].pop()
	if A2 == sorted(A2):
		cnt = 0
		for (i, idx1) in enumerate(idxs):
			for (j, idx2) in enumerate(idxs[i + 1:], i + 1):
				if idx1 > idx2:
					cnt += 1
		ans = min(ans, cnt)
if ans == INF:
	print(-1)
else:
	print(ans)


import sys
import itertools
import math

def first(i, a, b):
	if i % 2 == 0:
		return [a, b, i]
	else:
		return [b, a, i]

def chk(a, b):
	if m == l:
		for i in range(m - 1):
			if a[i][0] > b[i][0] or b[i][0] > a[i + 1][0]:
				return 0
		if a[m - 1][0] > b[m - 1][0]:
			return 0
	else:
		for i in range(l):
			if a[i][0] > b[i][0] or b[i][0] > a[i + 1][0]:
				return 0
	return 1

def cal(a, b):
	w = []
	if m == l:
		for i in range(l):
			w += [a[i][1], b[i][1]]
	else:
		for i in range(l):
			w += [a[i][1], b[i][1]]
		w.append(a[m - 1][1])
	return w
n = int(input())
(m, l) = (n - n // 2, n // 2)
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if n == 1:
	print(0)
	sys.exit()
x = [first(i, a[i], b[i]) for i in range(n)]
p = [i for i in range(n)]
ans = 1000000
for q in itertools.combinations(p, m):
	(tmpa, tmpb) = ([], [])
	for i in range(n):
		if i in q:
			tmpa.append([x[i][0], x[i][2]])
		else:
			tmpb.append([x[i][1], x[i][2]])
	tmpa.sort()
	tmpb.sort()
	if chk(tmpa, tmpb) == 1:
		t = cal(tmpa, tmpb)
		tans = 0
		for i in range(n):
			for j in range(i):
				if t[j] > t[i]:
					tans += 1
		ans = min(ans, tans)
print(ans if ans <= n * (n - 1) / 2 else -1)


import sys
input = sys.stdin.readline

class BIT:

	def __init__(self, size):
		self.bit = [0] * (size + 1)
		self.size = size

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

	def add(self, i, x):
		i += 1
		while i <= self.size:
			self.bit[i] += x
			i += i & -i
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = float('inf')
for b in range(1 << N):
	even = []
	odd = []
	for i in range(N):
		if b >> i & 1:
			if i % 2 == 0:
				even.append((A[i], i))
			else:
				odd.append((A[i], i))
		elif i % 2 == 0:
			odd.append((B[i], i))
		else:
			even.append((B[i], i))
	if len(even) != (N + 1) // 2 or len(odd) != N // 2:
		continue
	even.sort()
	odd.sort()
	num = []
	for i in range(len(odd)):
		num += [even[i], odd[i]]
	if N % 2 == 1:
		num += [even[-1]]
	ok = True
	for i in range(N - 1):
		if num[i][0] > num[i + 1][0]:
			ok = False
			break
	if not ok:
		continue
	tmp = 0
	bit = BIT(N)
	for i in range(1, N):
		bit.add(i, 1)
	for i in range(N):
		j = num[i][1]
		tmp += bit.sum(j) - i
		bit.add(0, 1)
		bit.add(j, -1)
	ans = min(ans, tmp)
print(ans if ans < float('inf') else -1)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
allpat = []
todo = [[]]
while todo:
	pat = todo.pop()
	if len(pat) == n // 2:
		allpat.append(pat)
		continue
	s = 0
	if pat:
		s = max(pat) + 1
	for i in range(s, n):
		todo.append(pat + [i])

def func(pat):
	ablev = []
	ablod = []
	for i in range(n):
		if i in pat:
			if i % 2 == 0:
				ablod.append([i, b[i]])
			else:
				ablod.append([i, a[i]])
		elif i % 2 == 0:
			ablev.append([i, a[i]])
		else:
			ablev.append([i, b[i]])
	ablev.sort(key=lambda x: x[1] * 20 + x[0])
	ablod.sort(key=lambda x: x[1] * 20 + x[0])
	now = 0
	ary = []
	for i in range(n // 2):
		if ablev[i][1] >= now:
			now = ablev[i][1]
			ary.append(ablev[i][0])
		else:
			return -1
		if ablod[i][1] >= now:
			now = ablod[i][1]
			ary.append(ablod[i][0])
		else:
			return -1
	if n % 2 == 1:
		if ablev[n // 2][1] >= now:
			now = ablev[i][1]
			ary.append(ablev[n // 2][0])
		else:
			return -1
	ret = 0
	for i in range(n):
		for j in range(n - 1, i, -1):
			if ary[j - 1] > ary[j]:
				(ary[j], ary[j - 1]) = (ary[j - 1], ary[j])
				ret += 1
	return ret
ans = float('inf')
for pat in allpat:
	t = func(pat)
	if t >= 0:
		ans = min(ans, t)
print(ans if ans != float('inf') else -1)


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
			elif 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)


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)


import itertools
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = [i for i in range(n)]

def add(k, x):
	while k <= n:
		data[k] += x
		k += k & -k

def get(k):
	s = 0
	while k:
		s += data[k]
		k -= k & -k
	return s
ans = 10 ** 18
for i in itertools.combinations(c, n // 2):
	j = list(set(c) - set(i))
	even = sorted([(a[k], k + 1) if k % 2 else (b[k], k + 1) for k in i])
	odd = sorted([(b[k], k + 1) if k % 2 else (a[k], k + 1) for k in j])
	prev = -1
	A = []
	for x in range(n):
		(Y, X) = divmod(x, 2)
		if X % 2:
			(now0, now1) = (even[Y][0], even[Y][1])
		else:
			(now0, now1) = (odd[Y][0], odd[Y][1])
		if prev > now0:
			break
		else:
			A.append(now1)
		prev = now0
	else:
		data = [0] * (n + 1)
		tmp = 0
		for (i, z) in enumerate(A):
			tmp += n - 1 - i - get(z)
			add(z, 1)
		ans = min(ans, tmp)
if ans == 10 ** 18:
	print(-1)
else:
	print(ans)


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)


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = N ** 2
for i in range(1 << N):
	L = [[] for _ in range(N)]
	T = [0] * N
	t = i
	for j in range(N):
		if t & 1:
			L[j] = [A[j], 1]
			T[j] = A[j]
		else:
			L[j] = [B[j], 0]
			T[j] = B[j]
		t >>= 1
	D = [0] * N
	T.sort()
	cnt = 0
	for j in range(N):
		c = 0
		for k in range(N):
			if D[k] == 0:
				if L[j][0] == T[k] and (j + 1 - L[j][1]) % 2 == k % 2:
					D[k] = 1
					cnt += j - c
					break
			else:
				c += 1
		else:
			break
	else:
		ans = min(ans, cnt)
if ans == N ** 2:
	print(-1)
else:
	print(ans)


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))
		elif 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)


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)


n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
res = []
for bit in range(2 ** n):
	if str(bin(bit)).count('1') % 2 == 1:
		continue
	odds = []
	evens = []
	for i in range(n):
		if bit >> i & 1:
			card = B[i]
			check = (i + 1) % 2
		else:
			card = A[i]
			check = i % 2
		if check == 1:
			odds.append([card, i + 1])
		else:
			evens.append([card, i + 1])
	if 0 <= len(evens) - len(odds) <= 1:
		odds.sort(reverse=True)
		evens.sort(reverse=True)
		now = 0
		pattern = []
		for _ in range(len(evens)):
			(num1, idx1) = evens.pop()
			if now <= num1:
				now = num1
				pattern.append(idx1)
				if odds:
					(num2, idx2) = odds.pop()
					if now <= num2:
						now = num2
						pattern.append(idx2)
					else:
						break
			else:
				break
		else:
			res.append(pattern)
if not res:
	print(-1)
	exit()
ans = []
for pattern in res:
	count = 0
	for i in range(n - 1):
		num = pattern[i]
		check = pattern[i + 1:]
		for t in check:
			if t < num:
				count += 1
	ans.append(count)
print(min(ans))


from collections import defaultdict

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 tento(xs):
	bit = Bit(max(xs) + 1)
	ans = 0
	for (i, p) in enumerate(xs):
		ans += i - bit.sum(p)
		bit.add(p, 1)
	return ans
N = int(input())
xs = list(map(int, input().split()))
ys = list(map(int, input().split()))
us = []
vs = []
for i in range(N):
	(a, b) = (xs[i], ys[i])
	if i % 2:
		us.append((a, i))
		vs.append((b, i))
	else:
		us.append((b, i))
		vs.append((a, i))
vs.sort()
r = 10 ** 18
for i in range(2 ** N):
	t = 0
	tt = 0
	rs = [0] * N
	rs2 = [0] * (N // 2)
	for j in range(N):
		if i % 2:
			if 2 * t < N:
				rs[t * 2] = vs[j]
			t += 1
		else:
			if 2 * tt + 1 < N:
				rs2[tt] = us[vs[j][1]]
			tt += 1
		i = i >> 1
	if t != (N + 1) // 2:
		continue
	rs2.sort()
	for i in range(N // 2):
		rs[i * 2 + 1] = rs2[i]
	(b, ff) = (0, 0)
	for (z, j) in rs:
		if b > z:
			ff = 1
			break
		b = z
	if ff:
		continue
	rs = [j + 1 for (_, j) in rs]
	r = min(r, tento(rs))
print(r if r != 10 ** 18 else -1)


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

def popcount(x):
	x = x - (x >> 1 & 6148914691236517205)
	x = (x & 3689348814741910323) + (x >> 2 & 3689348814741910323)
	x = x + (x >> 4) & 1085102592571150095
	x = x + (x >> 8)
	x = x + (x >> 16)
	x = x + (x >> 32)
	return x & 127
dp = [[INF for i in range(N)] for j in range(1 << N)]
for i in range(N):
	dp[1 << i][i] = i
for i in range(1 << N):
	for j in range(N):
		if i >> j & 1:
			if (popcount(i) - j) % 2 != 0:
				num = A[j]
			else:
				num = B[j]
			cnt = 0
			for k in range(N):
				if not i >> k & 1:
					if (popcount(i) - k) % 2 == 0:
						num2 = A[k]
					else:
						num2 = B[k]
					if num <= num2:
						dp[i | 1 << k][k] = min(dp[i | 1 << k][k], dp[i][j] + cnt)
					cnt += 1
ans = INF
for i in range(N):
	ans = min(ans, dp[(1 << N) - 1][i])
if ans == INF:
	print(-1)
else:
	print(ans)


import itertools
n = int(input())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]

def bitsum(BIT, i):
	s = 0
	while i > 0:
		s += BIT[i]
		i -= i & -i
	return s

def bitadd(BIT, i, x):
	while i <= 64:
		BIT[i] += x
		i += i & -i
	return BIT

def tentou(X):
	ret = 0
	BIT = [0] * 64
	BIT.insert(0, 0)
	for i1 in range(n):
		x = X[i1] + 1
		ret += i1 - bitsum(BIT, x)
		bitadd(BIT, x, 1)
	return ret
N = [int(i) for i in range(n)]
nn = 2 ** n
ans = float('inf')
for _ in range(n // 2 + 1):
	for com in itertools.combinations(N, 2 * _):
		i = 0
		for ura in com:
			i += 2 ** ura
		(E, O) = ([], [])
		for j in range(n):
			if i & 1 << j == 0:
				if j % 2 == 0:
					E.append(A[j] * 100 + j)
				else:
					O.append(A[j] * 100 + j)
			elif j % 2 == 0:
				O.append(B[j] * 100 + j)
			else:
				E.append(B[j] * 100 + j)
		if len(E) != (n + 1) // 2:
			continue
		else:
			E.sort()
			O.sort()
			chk = True
			C = [E[0] % 100]
			prev = E[0] // 100
			for i in range(1, n):
				ii = i // 2
				if i % 2 == 0:
					C.append(E[ii] % 100)
					if E[ii] // 100 < prev:
						chk = False
						break
					else:
						prev = E[ii] // 100
				else:
					C.append(O[ii] % 100)
					if O[ii] // 100 < prev:
						chk = False
						break
					else:
						prev = O[ii] // 100
		if chk:
			ans = min(ans, tentou(C))
print(-1 if ans == float('inf') else ans)


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
dp = [[10 ** 9 for _ in range(51)] for _ in range(1 << N)]
dp[0][0] = 0
for S in range(1 << N):
	j = bin(S).count('1')
	c = 0
	for i in range(N):
		if not S & 1 << i:
			k = A[i] if (i - j) % 2 == 0 else B[i]
			for l in range(k + 1):
				dp[S | 1 << i][k] = min(dp[S | 1 << i][k], dp[S][l] + c)
			c += 1
ans = min(dp[-1])
print(-1 if ans == 10 ** 9 else ans)


from itertools import *
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
Zlst = set([i for i in range(N)])
if N == 1:
	print(0)
	exit()
count = -1
for lst in combinations(range(N), N // 2 + N % 2):
	odds = [[A[i], i] if i % 2 == 0 else [B[i], i] for i in lst]
	even = [[B[i], i] if i % 2 == 0 else [A[i], i] for i in list(Zlst - set(lst))]
	oddsst = sorted(odds, key=lambda x: x[0])
	evenst = sorted(even, key=lambda x: x[0])
	temp = oddsst[0][0]
	lst = [oddsst[0][1]]
	for i in range(1, N):
		if i % 2 == 1:
			ntemp = evenst[i // 2]
		else:
			ntemp = oddsst[i // 2]
		if temp > ntemp[0]:
			flag = 0
			break
		else:
			flag = 1
			temp = ntemp[0]
			lst.append(ntemp[1])
	if flag:
		if count == -1:
			count = 10 ** 10
		tempcount = 0
		while flag:
			flag = 0
			for i in range(len(lst) - 1):
				if lst[i] > lst[i + 1]:
					(lst[i], lst[i + 1]) = (lst[i + 1], lst[i])
					tempcount += 1
					flag = 1
		count = min(count, tempcount)
print(count)


import sys, math, itertools, collections, bisect
input = lambda : sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf')
mod = 10 ** 9 + 7
mans = inf
ans = 0
count = 0
pro = 1

def f(n):
	count = 0
	while n:
		count += n % 2
		n //= 2
	return count
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
for bit in range(2 ** n):
	arr = []
	for i in range(n):
		if bit >> i & 1:
			arr.append((B[i], i))
		else:
			arr.append((A[i], i))
	i = 0
	flug = 1
	tmp = 0
	while flug:
		flug = 0
		for j in range(n - 1, i, -1):
			if arr[j - 1][0] > arr[j][0]:
				(arr[j - 1], arr[j]) = (arr[j], arr[j - 1])
				tmp += 1
				flug = 1
		i += 1
	stack = []
	for i in range(n):
		if abs(arr[i][1] - i) % 2 != bit >> arr[i][1] & 1:
			stack.append(arr[i][0] * 1000 + i)
	if len(stack) & 1:
		tmp = 1000
		stack.pop()
	while stack:
		p = stack.pop()
		q = stack.pop()
		if p - q & 1:
			tmp += p - q
		else:
			tmp += 1000
	mans = min(mans, tmp)
print(-1 if mans > 999 else mans)


import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10 ** 9))
write = lambda x: sys.stdout.write(x + '\n')
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
nums = [None] * n

def init(bit, values):
	for (i, v) in enumerate(values):
		update(bit, i, v)

def query(bit, i):
	res = 0
	while i > 0:
		res += bit[i]
		i -= i & -i
	return res

def update(bit, i, x):
	while i <= len(bit) - 1:
		bit[i] += x
		i += i & -i
	return

def tento(l):
	n = len(l)
	bit = [0] * (n + 1)
	ans = 0
	for (i, ind) in enumerate(l):
		ans += i - query(bit, ind + 1)
		update(bit, ind + 1, 1)
	return ans

def pp(func):

	def wrapped(*args, **keys):
		print(args, keys)
		val = func(*args, **keys)
		print(val)
		return val
	return wrapped

def sub(fr, to, bb):
	elist = []
	olist = []
	for (ff, bbb) in zip(fr, bb):
		if (ff + bbb) % 2:
			olist.append(ff)
		else:
			elist.append(ff)
	elist2 = []
	olist2 = []
	for item in to:
		if item % 2:
			olist2.append(item)
		else:
			elist2.append(item)
	if len(olist2) == len(olist) and len(elist2) == len(elist):
		olist.sort()
		elist.sort()
		if to[0] % 2 == 0:
			res = [(elist if i % 2 == 0 else olist)[i // 2] for i in range(len(to))]
			return res
		else:
			res = [(olist if i % 2 == 0 else elist)[i // 2] for i in range(len(to))]
			return res
	else:
		return None
best = 10 ** 9
for bit in range(1 << n):
	for i in range(n):
		val = b[i] if bit >> i & 1 else a[i]
		nums[i] = (val, i, bit >> i & 1)
	nums.sort()
	(prev, fr, bb) = nums[0]
	to = [0]
	fr = [fr]
	bb = [bb]
	valid = True
	array = []
	for i in range(1, n):
		(cv, cfr, cbb) = nums[i]
		if prev != cv:
			res = sub(fr, to, bb)
			if res is None:
				valid = False
				break
			array.extend(res)
			(prev, fr, bb) = (cv, [cfr], [cbb])
			to = [i]
		else:
			fr.append(cfr)
			to.append(i)
			bb.append(cbb)
	else:
		res = sub(fr, to, bb)
		if res is None:
			valid = False
		else:
			array.extend(res)
	if valid:
		ans = tento(array)
		best = min(best, ans)
if best == 10 ** 9:
	print(-1)
else:
	print(best)


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)


def tentousu(a):
	ans = 0
	for i in range(len(a)):
		for j in range(i + 1, len(a)):
			if a[i] > a[j]:
				ans += 1
	return ans
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(1, n, 2):
	(a[i], b[i]) = (b[i], a[i])
ans = inf = float('inf')
for i in range(2 ** n):
	s = bin(i)[2:].zfill(n)
	if s.count('0') != n // 2:
		continue
	if s.count('1') != n // 2 and s.count('1') != n // 2 + 1:
		continue
	ac = []
	bc = []
	for j in range(n):
		if s[j] == '1':
			ac.append((a[j], j))
		else:
			bc.append((b[j], j))
	ac.sort()
	bc.sort()
	x = []
	for j in range(n):
		if j % 2:
			x.append(bc[j // 2])
		else:
			x.append(ac[j // 2])
	f = False
	for j in range(1, n):
		if x[j - 1][0] > x[j][0]:
			f = True
	if f:
		continue
	m = []
	for j in range(n):
		m.append(x[j][1])
	ans = min(ans, tentousu(m))
if ans == inf:
	ans = -1
print(ans)


import sys
from itertools import combinations

def solve(N: int, A: 'List[int]', B: 'List[int]'):
	answer = 10 ** 18
	for c in combinations(range(N), N // 2):
		(even, odd) = ([], [])
		for i in range(N):
			if i in c:
				odd.append((A[i] if i % 2 == 1 else B[i], i))
			else:
				even.append((A[i] if i % 2 == 0 else B[i], i))
		even.sort()
		odd.sort()
		t = []
		ind = []
		for i in range(N // 2):
			t.append(even[i][0])
			t.append(odd[i][0])
			ind.append(even[i][1])
			ind.append(odd[i][1])
		if N % 2 == 1:
			t.append(even[-1][0])
			ind.append(even[-1][1])
		if t != sorted(t):
			continue
		tentousuu = 0
		for i in range(N - 1):
			for j in range(i + 1, N):
				if ind[i] > ind[j]:
					tentousuu += 1
		answer = min(answer, tentousuu)
	if answer == 10 ** 18:
		print(-1)
	else:
		print(answer)
	return

def main():

	def iterate_tokens():
		for line in sys.stdin:
			for word in line.split():
				yield word
	tokens = iterate_tokens()
	N = int(next(tokens))
	A = [int(next(tokens)) for _ in range(N)]
	B = [int(next(tokens)) for _ in range(N)]
	solve(N, A, B)
main()


import math
import itertools
import queue
import bisect
from collections import deque, defaultdict
import heapq as hpq
from sys import stdin, setrecursionlimit
ipt = stdin.readline
setrecursionlimit(10 ** 7)
mod = 10 ** 9 + 7
dir = [(-1, 0), (0, -1), (1, 0), (0, 1)]
alp = 'abcdefghijklmnopqrstuvwxyz'

def popcnt(n):
	return bin(n).count('1')

def main():
	n = int(ipt())
	card = [[int(i) for i in ipt().split()] for _ in range(2)]
	dp = [[10 ** 18] * n for i in range(2 ** n)]
	for i in range(1, 2 ** n):
		pi = popcnt(i)
		if pi == 1:
			for j in range(n):
				if i >> j & 1:
					dp[i][j] = 0
		else:
			pp = 0
			for j in range(n - 1, -1, -1):
				if i >> j & 1:
					nn = card[(pi - j + 1) % 2][j]
					pn = i - 2 ** j
					dpn = dp[pn]
					for k in range(n):
						if dp[i][j] > dpn[k] + pp:
							if card[(pi - k) % 2][k] <= nn:
								dp[i][j] = dpn[k] + pp
					pp += 1
	ans = min(dp[2 ** n - 1])
	if ans == 10 ** 18:
		ans = -1
	print(ans)
	return None
main()


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
AB = (A, B)
INF = 10 ** 18
ans = INF
for state in range(1 << N):
	even = []
	odd = []
	for i in range(N):
		isReverse = (state & 1 << i) >> i
		val = AB[isReverse][i]
		if i % 2 == 0:
			(even, odd)[isReverse].append((val, i))
		else:
			(odd, even)[isReverse].append((val, i))
	if len(even) != -(-N // 2) or len(odd) != N // 2:
		continue
	even.sort()
	odd.sort()
	odd.append((-1, -1))
	V = []
	P = []
	for ((l, i), (r, j)) in zip(even, odd):
		V.append(l)
		P.append(i)
		if r >= 0:
			V.append(r)
			P.append(j)
	if not all((l <= r for (l, r) in zip(V, V[1:]))):
		continue
	cnt = 0
	for (i, p) in enumerate(P):
		for q in P[:i]:
			if p < q:
				cnt += 1
	ans = min(ans, cnt)
print(ans if ans != INF else -1)


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)


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
dp = [[100100] * (1 << N) for _ in range(N)]
for i in range(N):
	dp[i][1 << i] = 0
for mask in range(1, 1 << N):
	mask_pop = format(mask, 'b').count('1')
	for j in range(N):
		if 1 << j & mask:
			if (j - mask_pop) % 2 == 1:
				cur_elem = A[j]
			else:
				cur_elem = B[j]
			prev_mask = mask & ~(1 << j)
			cost_delta = format(prev_mask & -1 << j, 'b').count('1')
			for t in range(N):
				if 1 << t & prev_mask:
					prev_elem = A[t] if (t - mask_pop - 1) % 2 == 1 else B[t]
					if prev_elem <= cur_elem:
						if dp[j][mask] > dp[t][prev_mask] + cost_delta:
							dp[j][mask] = dp[t][prev_mask] + cost_delta
ans = min((dp[i][-1] for i in range(N)))
if ans == 100100:
	print(-1)
else:
	print(ans)


from itertools import chain
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

def count_bit(x):
	res = 0
	while x:
		res += x % 2
		x >>= 1
	return res

def int2bin(x, N):
	res = [0] * N
	for i in range(N):
		res[N - 1 - i] = x % 2
		x >>= 1
	return res
inf = 10 ** 10
M = N // 2
ans = inf
for b in range(2 ** N):
	valid = True
	if count_bit(b) == M:
		odd_index = int2bin(b, N)
		evens = []
		odds = []
		for i in range(N):
			if odd_index[i]:
				if i % 2:
					odds.append((A[i], i))
				else:
					odds.append((B[i], i))
			elif i % 2:
				evens.append((B[i], i))
			else:
				evens.append((A[i], i))
		SE = sorted(evens)
		SO = sorted(odds)
		L = [None] * N
		L[::2] = SE
		L[1::2] = SO
		for ((a, _), (b, _)) in zip(L, L[1:]):
			if a > b:
				valid = False
				break
		if valid:
			L = list(zip(L, range(N)))
			L = sorted(L, key=lambda x: x[0][1])
			L = [(a, c) for ((a, b), c) in L]
			temp = 0
			for i in range(N):
				for j in range(i):
					if L[j] > L[i]:
						temp += 1
			ans = min(temp, ans)
if ans == inf:
	ans = -1
print(ans)


from itertools import combinations

class BinaryIndexedTree:

	def __init__(self, seq):
		self.size = len(seq)
		self.depth = self.size.bit_length()
		self.build(seq)

	def build(self, seq):
		data = seq
		size = self.size
		for (i, x) in enumerate(data):
			j = i + (i & -i)
			if j < size:
				data[j] += data[i]
		self.data = data

	def __repr__(self):
		return self.data.__repr__()

	def get_sum(self, i):
		data = self.data
		s = 0
		while i:
			s += data[i]
			i -= i & -i
		return s

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

	def find_kth_element(self, k):
		data = self.data
		size = self.size
		(x, sx) = (0, 0)
		dx = 1 << self.depth
		for i in range(self.depth - 1, -1, -1):
			dx = 1 << i
			if x + dx >= size:
				continue
			y = x + dx
			sy = sx + data[y]
			if sy < k:
				(x, sx) = (y, sy)
		return x + 1

def Inversion(seq):
	seq = [i + 1 for i in seq]
	N = len(seq)
	bit = BinaryIndexedTree([0] * (N + 1))
	inv = N * (N - 1) // 2
	for x in seq:
		inv -= bit.get_sum(x)
		bit.add(x, 1)
	return inv
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ptn = list(combinations(range(N), N // 2))
ans = -1
for p in ptn:
	evnline = []
	oddline = []
	for i in range(N):
		if i in p:
			evnline.append((A[i] if (i + 1) % 2 == 0 else B[i], i))
		else:
			oddline.append((B[i] if (i + 1) % 2 == 0 else A[i], i))
	line = [0] * N
	evnline.sort()
	oddline.sort()
	for (itr, val) in enumerate(evnline):
		line[itr * 2 + 1] = val
	for (itr, val) in enumerate(oddline):
		line[itr * 2] = val
	if all([j[0] >= i[0] for (i, j) in zip(line, line[1:])]):
		exchange_cnt = Inversion([i[1] for i in line])
		if ans == -1:
			ans = exchange_cnt
		else:
			ans = min(ans, exchange_cnt)
print(ans)


from collections import defaultdict
from operator import itemgetter
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = 1000
for n in range(2 ** N):
	n = bin(n)[2:]
	if n.count('1') % 2 != 0:
		continue
	n = '0' * (N - len(n)) + n
	l = []
	for i in range(N):
		if n[i] == '0':
			l.append([A[i], i])
		else:
			l.append([B[i], i + 1])
	inversion = 0
	for i in range(N):
		if inversion >= ans:
			break
		for j in range(i + 1, N):
			if l[i][0] > l[j][0]:
				inversion += 1
	if inversion >= ans:
		continue
	l.sort(key=itemgetter(0))
	d = defaultdict(list)
	for i in range(N):
		(v, j) = l[i]
		if (i - j) % 2 == 1:
			d[v].append(i)
	possible = True
	for v in d:
		if len(d[v]) % 2 == 1:
			possible = False
		else:
			for i in range(len(d[v]) // 2):
				if (d[v][2 * i + 1] - d[v][2 * i]) % 2 == 1:
					inversion += d[v][2 * i + 1] - d[v][2 * i]
				else:
					possible = False
					break
		if not possible:
			break
	if possible:
		ans = min(ans, inversion)
if ans == 1000:
	ans = -1
print(ans)


from collections import defaultdict

def main():
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	if all((a[0] == a[i] for i in range(n))):
		print(0)
		exit()
	pre = [1 << i for i in range(n)]
	bitcnt = [0] * (1 << n)
	bitcnt[1] = 1
	for i in range(1 << n - 1):
		bitcnt[2 * i] = bitcnt[i]
		bitcnt[2 * i + 1] = bitcnt[i] + 1
	DP = [defaultdict(lambda : float('inf')) for i in range(n)]
	for i in range(n):
		DP[i][1 << i] = 0
	s = defaultdict(lambda : float('inf'))
	for i in range(n - 1):
		nxt = [defaultdict(lambda : float('inf')) for i in range(n)]
		for j in range(n):
			last = a[j] if (i - j) % 2 == 0 else b[j]
			for (state, cost) in DP[j].items():
				for to in range(n):
					if state >> to & 1:
						continue
					nlast = a[to] if (i + 1 - to) % 2 == 0 else b[to]
					if last > nlast:
						continue
					nstate = state | pre[to]
					ncost = cost
					ncost += bitcnt[state >> to]
					if s[nstate, nlast] <= ncost:
						continue
					s[nstate, nlast] = ncost
					if nxt[to][nstate] > ncost:
						nxt[to][nstate] = ncost
		DP = nxt
	mask = (1 << n) - 1
	ans = float('inf')
	for i in range(n):
		ans = min(ans, DP[i][mask])
	if ans == float('inf'):
		print(-1)
	else:
		print(ans)
main()


from collections import deque
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = float('inf')
count = 0

def dfs(num, ro, re, bo, be):
	global ans, count
	count += 1
	if num == N:
		que = []
		ro.sort(reverse=True)
		re.sort(reverse=True)
		bo.sort(reverse=True)
		be.sort(reverse=True)
		ropos = -1
		repos = -1
		bopos = -1
		bepos = -1
		for i in range(N):
			if i % 2 == 0:
				if repos >= -len(re) and bopos >= -len(bo):
					(val1, num1) = re[repos]
					(val2, num2) = bo[bopos]
					if val1 > val2:
						que.append([val2, num2])
						bopos -= 1
					elif val2 > val1:
						que.append([val1, num1])
						repos -= 1
					elif num1 > num2:
						que.append([val2, num2])
						bopos -= 1
					else:
						que.append([val1, num1])
						repos -= 1
				elif repos >= -len(re):
					(val, num) = re[repos]
					que.append([val, num])
					repos -= 1
				elif bopos >= -len(bo):
					(val, num) = bo[bopos]
					que.append([val, num])
					bopos -= 1
				else:
					return 0
			elif ropos >= -len(ro) and bepos >= -len(be):
				(val1, num1) = ro[ropos]
				(val2, num2) = be[bepos]
				if val1 > val2:
					que.append([val2, num2])
					bepos -= 1
				elif val2 > val1:
					que.append([val1, num1])
					ropos -= 1
				elif num1 > num2:
					que.append([val2, num2])
					bepos -= 1
				else:
					que.append([val1, num1])
					ropos -= 1
			elif ropos >= -len(ro):
				(val, num) = ro[ropos]
				que.append([val, num])
				ropos -= 1
			elif bepos >= -len(be):
				(val, num) = be[bepos]
				que.append([val, num])
				bepos -= 1
			else:
				return 0
		for i in range(1, N):
			if que[i][0] < que[i - 1][0]:
				return 0
		temp = 0
		for i in range(1, N):
			for j in range(0, i):
				if que[i][1] < que[j][1]:
					temp += 1
		ans = min(ans, temp)
		return 0
	if num % 2 == 0:
		dfs(num + 1, ro, re + [[A[num], num]], bo, be)
		dfs(num + 1, ro, re, bo, be + [[B[num], num]])
	else:
		dfs(num + 1, ro + [[A[num], num]], re, bo, be)
		dfs(num + 1, ro, re, bo + [[B[num], num]], be)
dfs(0, [], [], [], [])
print(ans if ans != float('inf') else -1)


from itertools import combinations
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
even = [a[i] if i % 2 == 0 else b[i] for i in range(n)]
odd = [a[i] if i % 2 == 1 else b[i] for i in range(n)]
ans = 1001001001
for s in combinations(range(n), n // 2):
	s = set(s)
	t = set(range(n)) - s
	sdest = [(odd[i], i) for i in s]
	tdest = [(even[i], i) for i in t]
	sdest.sort()
	tdest.sort()
	origs = []
	z = []
	for i in range(n):
		if i & 1 == 0:
			origs.append(tdest[i // 2][1])
			z.append(tdest[i // 2][0])
		else:
			origs.append(sdest[(i - 1) // 2][1])
			z.append(sdest[(i - 1) // 2][0])
	if not all((x <= y for (x, y) in zip(z, z[1:]))):
		continue
	dests = [0] * n
	for (dest, orig) in enumerate(origs):
		dests[orig] = dest
	cnt = 0
	for i in range(n):
		for j in range(i):
			cnt += dests[j] > dests[i]
	ans = min(cnt, ans)
if ans == 1001001001:
	ans = -1
print(ans)


import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
from itertools import combinations, combinations_with_replacement
from operator import itemgetter

def main():
	mod = 1000000007
	inf = float('inf')
	sys.setrecursionlimit(10 ** 6)

	def input():
		return sys.stdin.readline().rstrip()

	def ii():
		return int(input())

	def isp():
		return input().split()

	def mi():
		return map(int, input().split())

	def mi_0():
		return map(lambda x: int(x) - 1, input().split())

	def lmi():
		return list(map(int, input().split()))

	def lmi_0():
		return list(map(lambda x: int(x) - 1, input().split()))

	def li():
		return list(input())

	def check_increasing(L):
		for i in range(1, n):
			if L[i][0] < L[i - 1][0]:
				return False
		return True

	def modified_merge(left, right):
		sorted_list = []
		(i, j, inv) = (0, 0, 0)
		buf_1 = left[:] + [float('inf')]
		buf_2 = right[:] + [float('inf')]
		for _ in range(len(left) + len(right)):
			if buf_1[i] < buf_2[j]:
				sorted_list.append(buf_1[i])
				i += 1
				inv += j
			else:
				sorted_list.append(buf_2[j])
				j += 1
		return (inv, sorted_list)

	def modified_merge_sort(L, i, j):
		if i + 1 == j:
			return (0, [L[i]])
		mid = (i + j) // 2
		(left_inv_cnt, left) = modified_merge_sort(L, i, mid)
		(right_inv_cnt, right) = modified_merge_sort(L, mid, j)
		(merge_inv_cnt, sorted_list) = modified_merge(left, right)
		return (left_inv_cnt + right_inv_cnt + merge_inv_cnt, sorted_list)

	def count_inversion(L):
		(cnt, _) = modified_merge_sort(L, 0, len(L))
		return cnt

	def calc_swapflip(L):
		return count_inversion(list(map(lambda x: x[1], L)))
	n = ii()
	A = lmi()
	B = lmi()
	ans = inf
	w = [(A[i], i, B[i]) if i % 2 == 0 else (B[i], i, A[i]) for i in range(n)]
	w.sort()
	for pattern in combinations(w, r=(n + 1) // 2):
		left = [(elm[2], elm[1], elm[0]) for elm in w if elm not in pattern]
		left.sort()
		concat = []
		for i in range(n // 2):
			concat.append(pattern[i])
			concat.append(left[i])
		if n % 2 == 1:
			concat.append(pattern[-1])
		if check_increasing(concat):
			op = calc_swapflip(concat)
			ans = min(ans, op)
	print(ans) if ans != inf else print(-1)
main()


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)


import sys
sys.setrecursionlimit(10 ** 6)
readline = sys.stdin.readline
read = sys.stdin.read
n = int(input())
a = [int(i) for i in readline().split()]
b = [int(i) for i in readline().split()]
L = range(n)
from itertools import combinations
ans = INF = 1000000
for I in combinations(L, n // 2):
	even = [(a[i] if i % 2 else b[i], i) for i in I]
	odd = [(b[i] if i % 2 else a[i], i) for i in range(n) if i not in I]
	odd.sort()
	even.sort()
	ok = 1
	for i in range(n // 2):
		if odd[i][0] > even[i][0]:
			ok = 0
			break
	for i in range(1, n - n // 2):
		if even[i - 1][0] > odd[i][0]:
			ok = 0
			break
	if ok:
		res = [0] * n
		for i in range(n // 2):
			res[2 * i + 1] = even[i][1]
		for i in range(n - n // 2):
			res[2 * i] = odd[i][1]
		cnt = 0
		for i in range(n):
			for j in range(i + 1, n):
				if res[i] > res[j]:
					cnt += 1
		ans = min(ans, cnt)
if ans == INF:
	print(-1)
else:
	print(ans)


from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heapify
import sys, bisect, math, itertools, fractions, pprint
sys.setrecursionlimit(10 ** 8)
mod = 10 ** 9 + 7
mod2 = 998244353
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpln(n):
	return list((int(sys.stdin.readline()) for i in range(n)))

def swap(l):
	cnt = 0
	for i in range(n):
		for j in range(i, n):
			if l[i] > l[j]:
				cnt += 1
	return cnt
n = inp()
a = inpl()
b = inpl()
card = []
res = INF
for i in range(n):
	card.append([a[i], b[i], i])
for flag in itertools.combinations(range(n), (n + 1) // 2):
	f = True
	odd_li = []
	odd_ind = [False] * n
	for (i, bit) in enumerate(flag):
		c = 1 if bit % 2 else 0
		odd_li.append([card[bit][c], bit])
		odd_ind[bit] = True
	if not f:
		continue
	odd_li.sort()
	even_li = []
	for i in range(n):
		c = 0 if i % 2 else 1
		if not odd_ind[i]:
			even_li.append([card[i][c], i])
	even_li.sort()
	if n % 2:
		for i in range(n // 2):
			if odd_li[i][0] <= even_li[i][0] <= odd_li[i + 1][0]:
				continue
			else:
				f = False
				break
	else:
		for i in range(n // 2):
			if i != n // 2 - 1:
				if odd_li[i][0] <= even_li[i][0] <= odd_li[i + 1][0]:
					continue
				else:
					f = False
					break
			elif odd_li[-1][0] <= even_li[-1][0]:
				continue
			else:
				f = False
				break
	if f:
		after_ind = []
		for i in range(n // 2):
			after_ind.append(odd_li[i][1])
			after_ind.append(even_li[i][1])
		if n % 2:
			after_ind.append(odd_li[-1][1])
		res = min(res, swap(after_ind))
print(-1 if res == INF else res)


import sys
from itertools import permutations, combinations
sys.setrecursionlimit(10 ** 7)
sr = lambda : sys.stdin.readline().rstrip()
ir = lambda : int(sr())
lr = lambda : list(map(int, sr().split()))
INF = 10 ** 5
answer = INF
N = ir()
if N == 1:
	print(0)
	exit()
A = lr()
B = lr()
for pattern in combinations(range(N), (N + 1) // 2):
	pattern = set(pattern)
	red = []
	blue = []
	for i in range(N):
		if i in pattern:
			red.append((B[i], i) if i & 1 else (A[i], i))
		else:
			blue.append((A[i], i) if i & 1 else (B[i], i))
	red.sort()
	blue.sort()
	result = []
	for i in range(N // 2):
		if red[i][0] > blue[i][0]:
			break
		if i + 1 < len(red) and red[i + 1][0] < blue[i][0]:
			break
		result.append(red[i][1])
		result.append(blue[i][1])
	else:
		if N & 1 and blue[-1][0] > red[-1][0]:
			continue
		if N & 1:
			result.append(red[-1][1])
		temp = 0
		used = set()
		for i in range(N):
			for x in used:
				if result[i] < x:
					temp += 1
			used.add(result[i])
		if temp < answer:
			answer = temp
print(answer if answer != INF else -1)


from itertools import combinations
n = int(input())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
even = []
odd = []
for (i, (a, b)) in enumerate(zip(As, Bs)):
	if i % 2 == 0:
		even.append(a)
		odd.append(b)
	else:
		even.append(b)
		odd.append(a)

def check(n, even, odd):
	prev = -10 ** 10
	ps = []
	for i in range(n):
		if i % 2 == 0:
			if prev > even[i // 2][0]:
				return (False, -1)
			else:
				ps.append(even[i // 2][1])
			prev = even[i // 2][0]
		else:
			if prev > odd[i // 2][0]:
				return (False, -1)
			else:
				ps.append(odd[i // 2][1])
			prev = odd[i // 2][0]
	return (True, ps)

def inversion(a):
	n = len(a)
	cnt = 0
	for i in range(n):
		for j in range(i + 1, n):
			if a[i] > a[j]:
				cnt += 1
	return cnt
INF = 10 ** 10
ans = 10 ** 10
for l in combinations(range(n), (n - 1) // 2 + 1):
	cnt = 0
	even_selected = [(even[i], i) for i in range(n) if i in l]
	odd_selected = [(odd[i], i) for i in range(n) if i not in l]
	even_selected.sort()
	odd_selected.sort()
	(is_possible, a) = check(n, even_selected, odd_selected)
	if is_possible:
		cnt = inversion(a)
		ans = min(cnt, ans)
if ans == INF:
	print(-1)
else:
	print(ans)


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

class BinaryIndexedTree:

	def __init__(self, seq):
		self.size = len(seq)
		self.depth = self.size.bit_length()
		self.build(seq)

	def build(self, seq):
		data = seq
		size = self.size
		for (i, x) in enumerate(data):
			j = i + (i & -i)
			if j < size:
				data[j] += data[i]
		self.data = data

	def __repr__(self):
		return self.data.__repr__()

	def get_sum(self, i):
		data = self.data
		s = 0
		while i:
			s += data[i]
			i -= i & -i
		return s

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

	def find_kth_element(self, k):
		data = self.data
		size = self.size
		(x, sx) = (0, 0)
		dx = 1 << self.depth
		for i in range(self.depth - 1, -1, -1):
			dx = 1 << i
			if x + dx >= size:
				continue
			y = x + dx
			sy = sx + data[y]
			if sy < k:
				(x, sx) = (y, sy)
		return x + 1

def Inversion(seq):
	N = len(seq)
	bit = BinaryIndexedTree([0] * (N + 1))
	inv = N * (N - 1) // 2
	for x in seq:
		inv -= bit.get_sum(x)
		bit.add(x, 1)
	return inv
INF = 10 ** 9
answer = INF
for I in itertools.combinations(range(N), (N + 1) // 2):
	J = [j for j in range(N) if j not in I]
	ODD = [(B[i] if i & 1 else A[i], i) for i in I]
	EV = [(A[i] if i & 1 else B[i], i) for i in J]
	ODD.sort()
	EV.sort()
	ind = [0] * N
	seq = [0] * N
	for i in range(0, N, 2):
		(seq[i], ind[i]) = ODD[i // 2]
	for i in range(1, N, 2):
		(seq[i], ind[i]) = EV[i // 2]
	if not all((x <= y for (x, y) in zip(seq, seq[1:]))):
		continue
	ind = [x + 1 for x in ind]
	n = Inversion(ind)
	if answer > n:
		answer = n
if answer == INF:
	answer = -1
print(answer)


n = int(input())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
INF = 1 << 20
dp = [[INF] * 55 for i in range(1 << n)]
dp[0][0] = 0
for b in range(1 << n):
	bitcnt = bin(b).count('1')
	cur = bitcnt
	rest = []
	for i in range(n):
		if not b & 1 << i:
			rest.append((i, cur))
			cur += 1
	for s in range(51):
		if dp[b][s] >= INF:
			continue
		for (i, cur) in rest:
			if abs(bitcnt - i) % 2 == 0:
				num = As[i]
			else:
				num = Bs[i]
			if num >= s:
				d = abs(bitcnt - cur)
				dp[b | 1 << i][num] = min(dp[b | 1 << i][num], dp[b][s] + d)
ans = min(dp[(1 << n) - 1])
print(ans if ans != INF else -1)


n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ab = lambda i, j: a[i] if abs(i - j) % 2 == 0 else b[i]
inf = 10 ** 9
dp = [n * [inf] for _ in range(1 << n)]
dp[0][0] = 0
for i in range(n):
	dp[1 << i][i] = i
for bit in range(1, 1 << n):
	m = [0] * n
	ii = 0
	for i in range(n):
		if bit & 1 << i:
			m[i] = ii
			ii += 1
	bit_count = ii
	for i in range(n):
		if bit & 1 << i == 0:
			m[i] = ii
			ii += 1
	for i in range(n):
		if bit & 1 << i:
			continue
		ci = ab(i, bit_count)
		for j in range(n):
			if bit & 1 << j == 0:
				continue
			cj = ab(j, bit_count - 1)
			if cj > ci:
				continue
			dp[bit | 1 << i][i] = min(dp[bit | 1 << i][i], dp[bit][j] + m[i] - bit_count)
ans = inf
for i in range(n):
	ans = min(ans, dp[-1][i])
if ans == inf:
	ans = -1
print(ans)


def main():
	from itertools import combinations
	n = int(input())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	cc = combinations(range(n), (n - 1) // 2 + 1)
	m = 10 ** 9
	if n == 1:
		print(0)
		return
	for c in cc:
		memo1 = []
		memo2 = []
		for i in c:
			if i % 2 == 0:
				memo1.append((a[i], i))
			else:
				memo1.append((b[i], i))
		for i in set(range(n)) - set(c):
			if i % 2 == 1:
				memo2.append((a[i], i))
			else:
				memo2.append((b[i], i))
		memo1.sort()
		memo2.sort()
		memo = []
		for i in range(n // 2):
			memo.append(memo1[i])
			memo.append(memo2[i])
		if n % 2 == 1:
			memo.append(memo1[i + 1])
		flag = 0
		for i in range(n - 1):
			if memo[i][0] > memo[i + 1][0]:
				flag = 1
				break
		if flag == 1:
			continue
		memo = [i for (j, i) in memo]
		cnt = 0
		for i in range(n - 1):
			for j in range(i + 1, n):
				if memo[i] > memo[j]:
					cnt += 1
		m = min(cnt, m)
	if m == 10 ** 9:
		print(-1)
	else:
		print(m)
main()


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

def getNum(i, j):
	return B[i] if abs(i - j) & 1 else A[i]
INF = 10 ** 9
dp = [[INF for _ in range(N)] for __ in range(1 << N)]
for i in range(N):
	dp[1 << i][i] = i
for m in range(1, 1 << N):
	cnt = bin(m).count('1')
	idx = dict()
	tmp = cnt
	for i in range(N):
		if m & 1 << i == 0:
			idx[i] = tmp
			tmp += 1
	for j in range(N):
		if m & 1 << j:
			continue
		num_j = getNum(j, cnt)
		for i in range(N):
			if m & 1 << i == 0:
				continue
			num_i = getNum(i, cnt - 1)
			if num_i > num_j:
				continue
			dp[m | 1 << j][j] = min(dp[m | 1 << j][j], dp[m][i] + idx[j] - cnt)
ans = INF
for i in range(N):
	ans = min(ans, dp[(1 << N) - 1][i])
print(ans if ans < INF else -1)


import sys
input = sys.stdin.readline

def count(P):
	res = 0
	BIT = [0] * (N + 1)

	def BIT_query(idx):
		res_sum = 0
		while idx > 0:
			res_sum += BIT[idx]
			idx -= idx & -idx
		return res_sum

	def BIT_update(idx, x):
		while idx <= N:
			BIT[idx] += x
			idx += idx & -idx
		return
	Pi = [None] * N
	for i in range(N):
		Pi[P[i]] = i
	for i in range(N):
		p = Pi[i]
		res += i - BIT_query(p + 1)
		BIT_update(p + 1, 1)
	return res
N = int(input())
A = tuple(map(int, input().split()))
B = tuple(map(int, input().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)


import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union

def main():
	mod = 1000000007
	inf = float('inf')
	sys.setrecursionlimit(10 ** 6)

	def input():
		return sys.stdin.readline().rstrip()

	def ii():
		return int(input())

	def isp():
		return input().split()

	def mi():
		return map(int, input().split())

	def mi_0():
		return map(lambda x: int(x) - 1, input().split())

	def lmi():
		return list(map(int, input().split()))

	def lmi_0():
		return list(map(lambda x: int(x) - 1, input().split()))

	def li():
		return list(input())
	n = ii()
	(A, B) = (lmi(), lmi())
	L = [A, B]
	M = max(max(A), max(B))
	dp = [[inf] * (M + 1) for _ in range(2 ** n)]
	dp[0][0] = 0
	for S in range(2 ** n):
		for k in range(M + 1):
			if dp[S][k] != inf:
				cnt = 0
				for i in range(n):
					if S & 1 << i:
						cnt += 1
				for i in range(n):
					if not S & 1 << i:
						card_front = L[(i - cnt) % 2][i]
						if card_front < k:
							continue
						inv = 0
						for j in range(i + 1, n):
							if S & 1 << j:
								inv += 1
						dp[S | 1 << i][card_front] = min(dp[S + (1 << i)][card_front], dp[S][k] + inv)
	ans = min(dp[S])
	if ans == inf:
		print(-1)
	else:
		print(ans)
main()


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
v = [[0, 0] for _ in range(N)]
s = []
ans = 500
for i in range(1 << N):
	tmp = 0
	for j in range(N):
		if i >> j & 1:
			v[j] = [B[j], j]
		else:
			v[j] = [A[j], j]
	for j in range(N):
		p = j
		while p and v[p][0] < v[p - 1][0]:
			(v[p], v[p - 1]) = (v[p - 1], v[p])
			tmp += 1
			p -= 1
	for j in range(N):
		if (i >> v[j][1]) + v[j][1] - j & 1:
			s.append(v[j][0] * 500 + j)
	if len(s) & 1:
		tmp = 500
		s.pop()
	while s:
		p = s.pop()
		q = s.pop()
		if p - q & 1:
			tmp += p - q
		else:
			tmp += 500
	ans = min(ans, tmp)
if ans < 500:
	print(ans)
else:
	print(-1)


import sys
input = sys.stdin.readline
N = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

def check(i):
	x = []
	for j in range(N):
		if i & 1 << j:
			x.append(b[j])
		else:
			x.append(a[j])
	sx = sorted(x)
	odd = [0] * 51
	even = [0] * 51
	for j in range(N):
		odd[sx[j]] += j % 2
		even[sx[j]] += j % 2 == 0
	for j in range(N):
		if i & 1 << j:
			if j % 2:
				even[x[j]] -= 1
			else:
				odd[x[j]] -= 1
		elif j % 2:
			odd[x[j]] -= 1
		else:
			even[x[j]] -= 1
	return min(min(odd), min(even)) >= 0

class BIT:

	def __init__(self, n):
		self.n = n
		self.data = [0] * (n + 1)
		self.el = [0] * (n + 1)

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

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

	def get(self, i, j=None):
		if j is None:
			return self.el[i]
		return self.sum(j) - self.sum(i)
res = float('inf')
for i in range(pow(2, N)):
	if check(i) == False:
		continue
	fwk = BIT(N)
	t = 0
	odd = []
	even = []
	for j in range(N):
		if i & 1 << j:
			if j % 2:
				even.append((b[j], j))
			else:
				odd.append((b[j], j))
		elif j % 2:
			odd.append((a[j], j))
		else:
			even.append((a[j], j))
	odd.sort(key=lambda x: x[0])
	even.sort(key=lambda x: x[0])
	ind = []
	for j in range(N):
		if j % 2:
			ind.append(odd[j // 2][1])
		else:
			ind.append(even[j // 2][1])
	for x in ind:
		t += fwk.get(x, N)
		fwk.add(x + 1, 1)
	res = min(res, t)
if res == float('inf'):
	print(-1)
else:
	print(res)


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
judge = False
ans = 10 ** 9
for i in range(2 ** N):
	even = []
	odd = []
	x = 0
	tmp = True
	for j in range(N):
		if i >> j & 1:
			if j % 2 == 1:
				even.append([B[j], j])
			else:
				odd.append([B[j], j])
		elif j % 2 == 1:
			odd.append([A[j], j])
		else:
			even.append([A[j], j])
	if N % 2 == 0:
		if len(even) != len(odd):
			continue
	elif len(even) - 1 != len(odd):
		continue
	even = sorted(even, key=lambda x: x[0])
	odd = sorted(odd, key=lambda x: x[0])
	ind = [0] * N
	for k in range(N // 2):
		o = odd[k]
		e = even[k]
		if o[0] < e[0]:
			tmp = False
			break
		if k != N // 2 - 1 or N % 2 == 1:
			if o[0] > even[k + 1][0]:
				tmp = False
				break
		ind[2 * k] = e[1]
		ind[2 * k + 1] = o[1]
	if tmp:
		if N % 2 == 1:
			ind[N - 1] = even[-1][1]
		for k in range(N):
			y = ind[k]
			x += abs(y - k)
			ind = [x + 1 if x < y and x >= k else x for x in ind]
		ans = min(ans, x)
		judge = True
if judge:
	print(ans)
else:
	print(-1)


def main():
	import sys
	input = sys.stdin.readline
	n = int(input())
	a = tuple(map(int, input().split()))
	b = tuple(map(int, input().split()))
	dg = 20
	pp = 20
	dp = [10 ** 5] * 10 ** 7
	new = set([])
	for i in range(n):
		s = 1 << i
		dp[s * pp + i] = i
		new.add(s * dg + i)
	for k in range(n - 1):
		tank = set([])
		if len(new) == 0:
			break
		for popelt in new:
			(s, idx) = (popelt // dg, popelt % dg)
			if (k - idx) % 2 == 0:
				fr = a[idx]
			else:
				fr = b[idx]
			cnt = 0
			for j in range(n):
				if s >> j & 1 == 0:
					if (j - k) % 2 == 1:
						val = a[j]
					else:
						val = b[j]
					if val >= fr and dp[(s + (1 << j)) * pp + j] > dp[s * pp + idx] + j - cnt:
						dp[(s + (1 << j)) * pp + j] = dp[s * pp + idx] + j - cnt
						tank.add((s + (1 << j)) * dg + j)
				else:
					cnt += 1
		new = tank
	res = 10 ** 5
	s = (2 ** n - 1) * pp
	for i in range(n):
		if res > dp[s + i]:
			res = dp[s + i]
	if res == 10 ** 5:
		print(-1)
	else:
		print(res)
main()


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])
		elif 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)


import sys
import itertools
INF = float('INF')
N = int(input())
AA = list(map(int, sys.stdin.readline().split()))
BB = list(map(int, sys.stdin.readline().split()))
cards = set()
for (i, (a, b)) in enumerate(zip(AA, BB)):
	if i % 2 == 0:
		cards.add((a, b, i))
	else:
		cards.add((b, a, i))

def solve(ii):
	tmp = 0
	for i in range(N):
		for j in range(i + 1, N):
			if ii[i] > ii[j]:
				tmp += 1
	return tmp
ans = INF
for Acards in itertools.combinations(cards, (N + 1) // 2):
	Bcards = cards - set(Acards)
	Ais = sorted([(card[0], card[2]) for card in Acards])
	Bis = sorted([(card[1], card[2]) for card in Bcards])
	bn = -1
	ii = []
	flag = False
	for i in range(N):
		if i % 2 == 0:
			(n, i) = Ais[i // 2]
		else:
			(n, i) = Bis[i // 2]
		if bn > n:
			flag = True
			break
		bn = n
		ii.append(i)
	if flag:
		continue
	ans = min(ans, solve(ii))
if ans == INF:
	print(-1)
else:
	print(ans)


from collections import defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10 ** 5)
input = sys.stdin.readline
sqrt = math.sqrt

def LI():
	return list(map(int, input().split()))

def LF():
	return list(map(float, input().split()))

def LI_():
	return list(map(lambda x: int(x) - 1, input().split()))

def II():
	return int(input())

def IF():
	return float(input())

def LS():
	return list(map(list, input().split()))

def S():
	return list(input().rstrip())

def IR(n):
	return [II() for _ in range(n)]

def LIR(n):
	return [LI() for _ in range(n)]

def FR(n):
	return [IF() for _ in range(n)]

def LFR(n):
	return [LI() for _ in range(n)]

def LIR_(n):
	return [LI_() for _ in range(n)]

def SR(n):
	return [S() for _ in range(n)]

def LSR(n):
	return [LS() for _ in range(n)]
mod = 1000000007
inf = 10000000000.0

def solve():
	n = II()
	A = LI()
	B = LI()
	bit_length = [0]
	for i in range(n):
		bit_length += [x + 1 for x in bit_length]
	dp = [[-1] * n for _ in range(1 << n)]
	for i in range(n):
		dp[1 << i][i] = 0
	for mask in range(1 << n):
		dpm = dp[mask]
		c = bit_length[mask]
		for i in range(n):
			if not 1 << i & mask or dpm[i] == -1:
				continue
			w = B[i] if 1 & i == c & 1 else A[i]
			cost = c
			for j in range(n):
				if 1 & mask >> j:
					cost -= 1
				else:
					v = B[j] if 1 & j != c & 1 else A[j]
					if v >= w:
						vl = dpm[i] + cost
						if dp[mask | 1 << j][j] == -1 or dp[mask | 1 << j][j] > vl:
							dp[mask | 1 << j][j] = vl
	ans = -1
	for i in range(n):
		if dp[-1][i] != -1:
			if ans == -1 or ans > dp[-1][i]:
				ans = dp[-1][i]
	print(ans)
	return
solve()


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
o = N // 2
e = N - o
import itertools
E = []
O = []
for i in range(N):
	if i % 2 == 0:
		E.append(i)
	else:
		O.append(i)
ANS = 10000

def mergecount(Z):
	cnt1 = 0
	z = len(Z)
	if z > 1:
		A1 = Z[:z >> 1]
		A2 = Z[z >> 1:]
		cnt1 += mergecount(A1)
		cnt1 += mergecount(A2)
		i1 = 0
		i2 = 0
		for i in range(z):
			if i2 == len(A2):
				Z[i] = A1[i1]
				i1 += 1
			elif i1 == len(A1):
				Z[i] = A2[i2]
				i2 += 1
			elif A1[i1] <= A2[i2]:
				Z[i] = A1[i1]
				i1 += 1
			else:
				Z[i] = A2[i2]
				i2 += 1
				cnt1 += z // 2 - i1
	return cnt1
for i in range(o + 1):
	X = list(itertools.combinations(E, i))
	Y = list(itertools.combinations(O, i))
	for j in range(len(X)):
		for k in range(len(Y)):
			ev = []
			od = []
			for n in range(N):
				if n % 2 == 0:
					if n in X[j]:
						od.append([B[n], n])
					else:
						ev.append([A[n], n])
				elif n in Y[k]:
					ev.append([B[n], n])
				else:
					od.append([A[n], n])
			ev.sort()
			od.sort()
			Z = []
			Num = 0
			F = 0
			for x in range(N):
				if x % 2 == 0:
					if Num > ev[x // 2][0]:
						F = 1
						break
					else:
						Num = ev[x // 2][0]
						Z.append(ev[x // 2][1])
				elif Num > od[x // 2][0]:
					F = 1
					break
				else:
					Num = od[x // 2][0]
					Z.append(od[x // 2][1])
			if F == 0:
				tcnt = mergecount(Z)
			if F == 0 and tcnt < ANS:
				ANS = tcnt
if ANS == 10000:
	print(-1)
else:
	print(ANS)


class BIT:

	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 = i + 1
		while i <= self.n:
			self.bit[i] += val
			i += i & -i

	def get_sum(self, 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)


import itertools
n = int(input())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]
N = [int(i) for i in range(n)]
nn = 2 ** n
ans = float('inf')
for _ in range(n // 2 + 1):
	for com in itertools.combinations(N, 2 * _):
		i = 0
		for ura in com:
			i += 2 ** ura
		(E, O) = ([], [])
		for j in range(n):
			if i & 1 << j == 0:
				if j % 2 == 0:
					E.append(A[j] * 100 + j)
				else:
					O.append(A[j] * 100 + j)
			elif j % 2 == 0:
				O.append(B[j] * 100 + j)
			else:
				E.append(B[j] * 100 + j)
		if len(E) != (n + 1) // 2:
			continue
		else:
			E.sort()
			O.sort()
			chk = True
			C = [E[0] % 100]
			prev = E[0] // 100
			for i in range(1, n):
				ii = i // 2
				if i % 2 == 0:
					C.append(E[ii] % 100)
					if E[ii] // 100 < prev:
						chk = False
						break
					else:
						prev = E[ii] // 100
				else:
					C.append(O[ii] % 100)
					if O[ii] // 100 < prev:
						chk = False
						break
					else:
						prev = O[ii] // 100
		if chk:
			ten = 0
			for i1 in range(n):
				for i2 in range(i1 + 1, n):
					if C[i1] > C[i2]:
						ten += 1
			ans = min(ans, ten)
print(-1 if ans == float('inf') else ans)


class BinaryIndexedTree:

	def __init__(self, n):
		self.bit = [0] * n

	def add(self, i, x):
		i += 1
		while i <= len(self.bit):
			self.bit[i - 1] += x
			i += i & -i

	def sum_1(self, i):
		a = 0
		i += 1
		while i:
			a += self.bit[i - 1]
			i -= i & -i
		return a

	def sum(self, i, j):
		a = self.sum_1(j - 1)
		if i != 0:
			a -= self.sum_1(i - 1)
		return a

def tentousu(a):
	bit = BinaryIndexedTree(n)
	b = [0] * n
	for i in range(n):
		b[a[i]] = i
	ans = 0
	for i in range(n):
		j = b[i] + bit.sum(b[i] + 1, n)
		ans += j - i
		bit.add(b[i], 1)
	return ans
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(1, n, 2):
	(a[i], b[i]) = (b[i], a[i])
ans = inf = float('inf')
for i in range(2 ** n):
	s = bin(i)[2:].zfill(n)
	if s.count('0') != n // 2:
		continue
	ac = []
	bc = []
	for j in range(n):
		if s[j] == '1':
			ac.append((a[j], j))
		else:
			bc.append((b[j], j))
	ac.sort()
	bc.sort()
	x = []
	for j in range(n):
		if j % 2:
			x.append(bc[j // 2])
		else:
			x.append(ac[j // 2])
	f = False
	for j in range(1, n):
		if x[j - 1][0] > x[j][0]:
			f = True
	if f:
		continue
	m = []
	for j in range(n):
		m.append(x[j][1])
	ans = min(ans, tentousu(m))
if ans == inf:
	ans = -1
print(ans)


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()


import itertools
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
odds = []
evens = []
for i in range(n):
	if i % 2 == 0:
		odds.append([a[i], i])
		evens.append([b[i], i])
	else:
		odds.append([b[i], i])
		evens.append([a[i], i])
odds = sorted(odds)
evens = sorted(evens)
inds = [i for i in range(n)]
ans = 10000000000
exist = 0
half = (n - 1) // 2 + 1
for v in itertools.combinations(inds, half):
	real_v = [odds[i][1] for i in v]
	real_nokori = []
	for i in range(n):
		if not evens[i][1] in real_v:
			real_nokori.append(evens[i][1])
	nokori = []
	for i in range(n):
		if evens[i][1] in real_nokori:
			nokori.append(i)
	moge = 1
	if n % 2 == 0:
		for i in range(half):
			if evens[nokori[i]][0] < odds[v[i]][0]:
				moge = 0
	else:
		for i in range(n - half):
			if evens[nokori[i]][0] < odds[v[i]][0]:
				moge = 0
	for i in range(half - 1):
		if evens[nokori[i]][0] > odds[v[i + 1]][0]:
			moge = 0
	if moge != 1:
		continue
	else:
		exist = 1
	tar = []
	for i in range(n):
		if i % 2 == 0:
			tar.append(real_v[i // 2])
		else:
			tar.append(real_nokori[(i - 1) // 2])
	dist = 0
	for i in range(n):
		for mo in range(i + 1, n):
			if tar[mo] < tar[i]:
				dist += 1
	if dist < ans:
		ans = dist
if exist:
	print(ans)
else:
	print(-1)


from itertools import product

def solve(n, a_list, b_list):
	res = 10 ** 9 + 7
	for p in product([0, 1], repeat=n):
		if sum(p) % 2 == 1:
			continue
		r = 0
		c_list = [a for a in a_list]
		for i in range(n):
			if p[i] == 1:
				c_list[i] = b_list[i]
		c_list_s = list(sorted(c_list))
		used = [0] * n
		d_list = [0] * n
		for k in range(n):
			j = -1
			for i in range(n):
				if c_list[i] == c_list_s[k] and (not used[i]) and ((i - k + p[i]) % 2 == 0):
					used[i] = 1
					j = i
					break
			if j >= 0:
				d_list[j] = k
			else:
				r += 10 ** 9 + 7
		for i in range(n - 1):
			for j in range(i + 1, n):
				if d_list[i] > d_list[j]:
					r += 1
		res = min(res, r)
	if res < 10 ** 9 + 7:
		return res
	else:
		return -1

def main():
	n = int(input())
	a_list = list(map(int, input().split()))
	b_list = list(map(int, input().split()))
	res = solve(n, a_list, b_list)
	print(res)

def test():
	assert solve(3, [3, 4, 3], [3, 2, 3]) == 1
	assert solve(2, [2, 1], [1, 2]) == -1
	assert solve(4, [1, 2, 3, 4], [5, 6, 7, 8]) == 0
test()
main()


def iter_bit(k, LIMIT):
	v = (1 << k) - 1
	while v < LIMIT:
		yield v
		x = v & -v
		y = v + x
		v = (v & ~y) // x >> 1 | y

def solve(n, cards):
	dp = [{} for _ in range(1 << n)]
	dp[-1][0] = 0
	LIMIT = 1 << n
	for d in range(n):
		for state in iter_bit(n - d, LIMIT):
			scores = dp[state]
			k = state
			curr = 0
			while k:
				b = k & -k
				i = b.bit_length() - 1
				num = cards[i][(d - i) % 2]
				next_dp = dp[state ^ b]
				for (left_num, score) in scores.items():
					if left_num > num:
						continue
					ns = score + curr
					if num not in next_dp or next_dp[num] > ns:
						next_dp[num] = ns
				k ^= b
				curr += 1
	if len(dp[0]) > 0:
		return min(dp[0].values())
	else:
		return -1
n = int(input())
aaa = list(map(int, input().split()))
bbb = list(map(int, input().split()))
cards = list(zip(aaa, bbb))
print(solve(n, cards))


import sys
from itertools import combinations
input = sys.stdin.readline
n = int(input())
a = [int(x) for x in input().strip().split()]
b = [int(x) for x in input().strip().split()]
all_cards = []
for (i, (aa, bb)) in enumerate(zip(a, b)):
	if i % 2:
		(aa, bb) = (bb, aa)
	all_cards.append([aa, bb, i])

def cnt(l):
	ret = 0
	for i in range(len(l) - 1):
		for j in range(i + 1, len(l)):
			if l[i][1] > l[j][1]:
				ret += 1
	return ret
ans = float('inf')
for cards in combinations(all_cards, (n + 1) // 2):
	acards = []
	for card in cards:
		acards.append([card[0], card[2]])
	bcards = []
	for card in all_cards:
		if [card[0], card[2]] not in acards:
			bcards.append([card[1], card[2]])
	acards.sort()
	bcards.sort()
	abcards = []
	for i in range(len(bcards)):
		abcards.extend([acards[i], bcards[i]])
	else:
		if n % 2:
			abcards.append(acards[-1])
	if abcards != sorted(abcards, key=lambda x: x[0]):
		continue
	ans = min(ans, cnt(abcards))
if ans == float('inf'):
	ans = -1
print(ans)


import bisect
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = 10 ** 9 + 7
for i in range(2 ** N):
	card = [[], []]
	num = []
	iii = i
	for j in range(N):
		if i & 1:
			num.append(B[j])
			card[(j + 1) % 2].append(j)
		else:
			num.append(A[j])
			card[j % 2].append(j)
		i >>= 1
	if len(card[1]) != N // 2:
		continue
	card[0].sort(key=lambda x: [num[x], x])
	card[1].sort(key=lambda x: [num[x], x])
	hoge = []
	for i in range(N):
		hoge.append(card[i % 2][i // 2])
	flag = True
	for i in range(N - 1):
		if num[hoge[i]] > num[hoge[i + 1]]:
			flag = False
	if flag:
		huga = []
		count = 0
		for i in range(N):
			l = bisect.bisect_left(huga, hoge[i])
			huga.insert(l, hoge[i])
			count += i - l
		if count < ans:
			ans = count
if ans >= 10 ** 9:
	print(-1)
else:
	print(ans)