#ABC150C

import itertools

n = int(eval(input()))

ls = [i+1 for i in range(n)]

p = list(map(int,input().split()))

q = list(map(int,input().split()))

v = [ list(v) for v in itertools.permutations(ls, n)]

a, b = v.index(p), v.index(q)

print((abs(a-b)))
#ABC150C

import itertools

n = int(eval(input()))

p = tuple(map(int,input().split()))

q = tuple(map(int,input().split()))

ls = list(itertools.permutations(list(range(1,n+1))))

print((abs(ls.index(p)-ls.index(q))))
# ABC150C
import itertools

n = int(eval(input()))
ls = [i + 1 for i in range(n)]
p = list(map(int, input().split()))
q = list(map(int, input().split()))
v = [list(v) for v in itertools.permutations(ls, n)]
a, b = v.index(p), v.index(q)
print((abs(a - b)))

# ABC150C
import itertools

n = int(eval(input()))
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
ls = list(itertools.permutations(list(range(1, n + 1))))
print((abs(ls.index(p) - ls.index(q))))

-ls = [i + 1 for i in range(n)] -p = list(map(int, input().split())) -q = list(map(int, input().split())) -v = [list(v) for v in itertools.permutations(ls, n)] -a, b = v.index(p), v.index(q) -print((abs(a - b))) +p = tuple(map(int, input().split())) +q = tuple(map(int, input().split())) +ls = list(itertools.permutations(list(range(1, n + 1)))) +print((abs(ls.index(p) - ls.index(q))))