n = int(eval(input()))

p = eval(input())

q = eval(input())



import itertools



l = []

for i in range(1, n+1):

    l.append(str(i))



ans = []

for v in itertools.permutations(l):

    ans.append(" ".join(v))



a = ans.index(p)

b = ans.index(q)

print((abs(a-b)))
n = int(eval(input()))

P = tuple(map(str, input().split()))

Q = tuple(map(str, input().split()))



l = []

for i in range(1, n+1):

	l.append(str(i))

	

import itertools

count = 0

for x in itertools.permutations(l):

	if x == P:

		p = count

	if x == Q:

		q = count

	count += 1

	

print((abs(p-q)))
n = int(eval(input()))
p = eval(input())
q = eval(input())
import itertools

l = []
for i in range(1, n + 1):
    l.append(str(i))
ans = []
for v in itertools.permutations(l):
    ans.append(" ".join(v))
a = ans.index(p)
b = ans.index(q)
print((abs(a - b)))

n = int(eval(input()))
P = tuple(map(str, input().split()))
Q = tuple(map(str, input().split()))
l = []
for i in range(1, n + 1):
    l.append(str(i))
import itertools

count = 0
for x in itertools.permutations(l):
    if x == P:
        p = count
    if x == Q:
        q = count
    count += 1
print((abs(p - q)))

-p = eval(input()) -q = eval(input()) -import itertools - +P = tuple(map(str, input().split())) +Q = tuple(map(str, input().split())) -ans = [] -for v in itertools.permutations(l): -    ans.append(" ".join(v)) -a = ans.index(p) -b = ans.index(q) -print((abs(a - b))) +import itertools + +count = 0 +for x in itertools.permutations(l): +    if x == P: +        p = count +    if x == Q: +        q = count +    count += 1 +print((abs(p - q)))