Problem:
 Score : 300 points    Problem Statement We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N) ).  There are N! possible permutations of size N . Among them, let P and Q be the a -th and b -th lexicographically smallest permutations, respectively. Find |a - b| .      Notes For two sequences X and Y , X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k .      Constraints  2 \leq N \leq 8  P and Q are permutations of size N .         Input Input is given from Standard Input in the following format:  N  P_1  P_2  ...  P_N  Q_1  Q_2  ...  Q_N       Output Print |a - b| .        Sample Input 1 3
1 3 2
3 1 2      Sample Output 1 3  There are 6 permutations of size 3 : (1,~2,~3) , (1,~3,~2) , (2,~1,~3) , (2,~3,~1) , (3,~1,~2) , and (3,~2,~1) . Among them, (1,~3,~2) and (3,~1,~2) come 2 -nd and 5 -th in lexicographical order, so the answer is |2 - 5| = 3 .       Sample Input 2 8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1      Sample Output 2 17517       Sample Input 3 3
1 2 3
1 2 3      Sample Output 3 0

Solution (Python):
import itertools as it

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))

a = 0
b = 0
n = it.permutations(range(1, N + 1), N)
for i, e in enumerate(n):
    if P == e:
        a = i
    if Q == e:
        b = i

print(abs(a - b))

Solution (Python):
import itertools

N = int(input())
lis = [x+1 for x in range(N)]
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
i = 1

for p in itertools.permutations(lis):
  for j in range(N):
    if p[j] != P[j]:
      break
    j += 1
  if j == N:
    pp = i
  for j in range(N):
    if p[j] != Q[j]:
      break
    j += 1
  if j == N:
    pq = i
  i += 1

print(abs(pp-pq))

Solution (Python):
import itertools

N = int(input())
P = ' '.join(list(input().split()))
Q = ' '.join(list(input().split()))
perm = [1 + i for i in range(N)]
for i, v in enumerate(itertools.permutations(perm)):
    v = ' '.join(list(map(str, v)))
    if v == P:
        p = i
    if v == Q:
        q = i
print(abs(p - q))

Solution (Python):
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
from itertools import permutations
i = 0
for permu_lis in permutations(range(1, n + 1)):
  i += 1
  if list(permu_lis) == p:
    a = i
  if list(permu_lis) == q:
    b = i
print(abs(a - b))

Solution (Python):
import itertools
n = int(input())
l = [(i+1) for i in range(n)]
tupleperm = tuple(itertools.permutations(l))
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
print(abs(tupleperm.index(p)-tupleperm.index(q)))

Solution (Python):
import itertools
import sys
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
if p == q:
    print('0')
    sys.exit(0)
num_p = num_q = 0
counter = 0

for pairs in itertools.permutations((range(1, n + 1))):
    lp = list(pairs)
    counter += 1
    if p == lp:
        num_p = counter
    elif q == lp:
        num_q = counter
print(abs(num_p - num_q))

Solution (Python):

import itertools
def myAnswer(N:int,P:list,Q:list) -> int:
   l = [i for i in range(1,N+1)]
   a = 0
   b = 0
   for n,i in enumerate(itertools.permutations(l,N)):
      if(i == tuple(P)):
         a = n
      if(i == tuple(Q)):
         b = n
   return abs(a - b)

   

def modelAnswer():
   tmp=1
def main():
   N = int(input())
   P = list(map(int,input().split()))
   Q = list(map(int,input().split()))
   print(myAnswer(N,P,Q))

if __name__ == '__main__':
   main()

Solution (Python):
from itertools import permutations

N = int(input())
P = input()
Q = input()

a = -1
b = -1
base = list(range(1, N + 1))
for i, l in enumerate(permutations(base, N)):
    s = ' '.join([str(x) for x in l])
    if (P == s):
        a = i
    if (Q == s):
        b = i
print(abs(a - b))

Solution (Python):
from itertools import permutations as pmt

N = int(input())
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]

a,b = None,None
i = 0
for od in pmt([i+1 for i in range(N)]):
    order = list(od)
    if P == order:
        a = i
    if Q == order:
        b = i
    i += 1
print(abs(a-b))

Solution (Python):
import sys
from itertools import permutations
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    P=tuple(map(int,input().split()))
    Q=tuple(map(int,input().split()))
    p_list=list(permutations(range(1,n+1)))
    print(abs(p_list.index(Q)-p_list.index(P)))

if __name__=='__main__':
    main()

Solution (Python):
import sys
from itertools import permutations
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    P=tuple(map(int,input().split()))
    Q=tuple(map(int,input().split()))
    p_list=list(permutations(range(1,n+1)))
    print(abs(p_list.index(Q)-p_list.index(P)))

if __name__=='__main__':
    main()

Solution (Python):
import sys
from itertools import permutations
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    P=tuple(map(int,input().split()))
    Q=tuple(map(int,input().split()))
    p_list=list(permutations(range(1,n+1)))
    print(abs(p_list.index(Q)-p_list.index(P)))

if __name__=='__main__':
    main()

Solution (Python):
import sys
from itertools import permutations
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    P=tuple([int(_) for _ in input().split()])
    Q=tuple([int(_) for _ in input().split()])
    p_list=list(permutations(list(range(1,n+1))))
    print(abs(p_list.index(Q)-p_list.index(P)))

if __name__=='__main__':
    main()

Solution (Python):
from itertools import permutations
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
per = list(permutations([i+1 for i in range(n)]))
ans = abs(per.index(p)-per.index(q))
print(ans)

Solution (Python):
import numpy as np
import math
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))

p = np.arange(N) + 1

def dict_num(arr, N):
    n = 1
    num_used = []
    for i in range(N):
        k = 0
        for a in range(1, arr[i]):
            if a in num_used:
                k += 1
        n += (arr[i] - 1 - k) * math.factorial(N - i - 1)
        num_used.append(arr[i])
    return n

p_n = dict_num(P, N)
q_n = dict_num(Q, N)
print(abs(p_n - q_n))

Solution (Python):
import itertools
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
p_ = sorted(p)
ans = list(itertools.permutations(p_))

p
num_p = 0
num_q = 0
for i in range(len(ans)):
    
    if list(ans[i]) == p: num_p = i
    if list(ans[i]) == q: num_q = i
print(abs(num_p-num_q))

Solution (Python):
import itertools

n = int(input())
ps = tuple(map(int, input().split()))
qs = tuple(map(int, input().split()))

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

pl = [v for v in itertools.permutations(l)]

a = pl.index(ps)
b = pl.index(qs)

print(abs(a-b))

Solution (Python):
import itertools

N = [ i+1 for i in range(int(input()))]
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
V = []

for v in itertools.permutations(N, len(N)):
    V.append(v)
P_ind = V.index(P)
Q_ind = V.index(Q)

print(abs(P_ind - Q_ind))

Solution (Python):
import itertools
n = int(input())
ps = tuple(map(int, input().split()))
qs = tuple(map(int, input().split()))

perm = list(sorted(itertools.permutations(range(1, n + 1))))
for i in range(len(perm)):
    p = perm[i]
    if p == ps:
        a = i
    if p == qs:
        b = i

print(abs(a - b))

Solution (Python):
from itertools import permutations

N = int(input())
p = map(int,input().split())
q = map(int,input().split())

p = tuple(p)
q = tuple(q)

A = sorted(list(permutations(p,N)))

a = A.index(p)
b = A.index(q)

print(abs(a-b))

Solution (Python):
import itertools
n = int(input())

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

lista = list(itertools.permutations(range(1, n + 1)))
print(abs(lista.index(p) - lista.index(q)))

Solution (Python):
import itertools
n = int(input())
p = tuple(map(str, input().split()))
q = tuple(map(str, input().split()))
pc = 0
qc = 0
ans_l = list(itertools.permutations(p, n))
ans_l = sorted(ans_l)
for i in ans_l:
    pc += 1
    if i == p:
        break
for i in ans_l:
    qc += 1
    if i == q:
        break
print(abs(pc - qc))

Solution (Python):
def kaijo(n):
    if n == 1 or n == 0:
        return 1
    else:
        return n * kaijo(n-1)

def counter(P):
    c = 0
    i = 0
    while i < len(P):
        c += (P[0]-1) * kaijo(len(P)-1)
        q = 1
        while q < len(P):
            if P[q] > P[0]:
                P[q] -= 1
            q += 1
        P = P[1:]
    return c

n = int(input())
P = list(map(int,input().split(' ')))
Q = list(map(int,input().split(' ')))
print(abs(counter(P)-counter(Q)))

Solution (Python):
import math
import itertools

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

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

a = 0
b = 0

for i in range(math.factorial(n)):
    if iter[i] == p:
        a = i
    if iter[i] == q:
        b = i

print(abs(a-b))

Solution (Python):
import itertools
N = int(input())
P = list(map(int,input().split()))
P = tuple(P)
Q = list(map(int,input().split()))
Q = tuple(Q)
dic = list(itertools.permutations(range(1,N+1)))
dic.sort()
a = 0
b = 0
for i in range(len(dic)):
    if dic[i] == P:
        a = i
    if dic[i] == Q:
        b = i
print(abs(a-b))

Solution (Python):
import itertools
N = int(input())
l = list(itertools.permutations([i for i in range(1, N + 1)]))
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
P_c = 0
Q_c = 0
for i in range(len(l)):
    if l[i] == P:
        P_c = i
    if l[i] == Q:
        Q_c = i
print(abs(P_c - Q_c))

Solution (Python):
import math
import itertools
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
a,b = 0,0
seq = [i for i in range(1,n+1)]
k = list(itertools.permutations(seq))
for i in range(math.factorial(n)):
    if k[i] == p:
        a = i
    if k[i] == q:
        b = i
print(abs(a-b))

Solution (Python):
import itertools
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
per = []
for v in itertools.permutations(P):
    per.append(''.join(str(n) for n in v))
per.sort()

a = per.index(''.join(str(n) for n in P))
b = per.index(''.join(str(n) for n in Q))
ans = abs(a - b)
print(ans)

Solution (Python):
import itertools
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))

l=[]
for i in range(n):
    l.append(i+1)

nlist=[]
for i in itertools.permutations(l,r=n):
        nlist.append(list(i))




for i in range(len(nlist)):
    if nlist[i]==p:
        po=i
    if nlist[i]==q:
        qo=i

print(abs(qo-po))

Solution (Python):
import itertools
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
ls = [i+1 for i in range(N)]
per = []
for j in itertools.permutations(ls,N):
    per.append(j)
print(abs(per.index(P) - per.index(Q)))

Solution (Python):
import itertools 
n = int(input())
s = list(map(int,input().split()))
q = list(map(int,input().split()))
z = 0
l = [i for i in  range(1,n+1)]
l1 = itertools.permutations(l)
for i in l1:
  z += 1
  if list(i)==s:
    a =z
  if list(i)==q:
    c = z
print(abs(c-a))

Solution (Python):
import math

def rank_checker(P):
  rank = 1
  N = len(P)
  L = list(range(1, N + 1))
  for i in range(N):
    weight = L.index(P[i])
    penalty = math.factorial(len(L) - 1)
    rank += weight * penalty
    L.pop(weight)
  return rank


_ = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))

rankP = rank_checker(P)
rankQ = rank_checker(Q)
print(abs(rankP - rankQ))

Solution (Python):
from collections import defaultdict, deque
import sys, heapq, bisect, math, itertools, string, queue, copy, time
from fractions import gcd
import numpy as np
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 = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
a = 0
b = 0
k = 0

for i in itertools.permutations(range(1,n+1)):
    k += 1
    if i == p:
        a = k
    if i == q:
        b = k
ans = abs(a-b)
print(ans)

Solution (Python):
from itertools import permutations
import bisect

N = int(input())
P = input().replace(' ', '')
Q = input().replace(' ', '')

t = [''.join(list(map(str, i))) for i in permutations(range(1, N + 1))]
a = bisect.bisect_left(t, P)
b = bisect.bisect_left(t, Q)

print(abs(a-b))

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

import itertools

n = int(readline())
p = tuple(map(int, readline().split()))
q = tuple(map(int, readline().split()))
ans = list(itertools.permutations([(i + 1) for i in range(n)]))
print(abs(ans.index(p) - ans.index(q)))

Solution (Python):
from itertools import permutations 
n = int(input())
p = list(map(int, input().split())) 
q = list(map(int, input().split()))
 
i = 0
for x in permutations(range(1, n+1)):
    i += 1
    if list(x) == p:
        a = i
    if list(x) == q:
        b = i

print(abs(a-b))

Solution (Python):
import math
import itertools

N=int(input())
N_fac=math.factorial(N)
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
p=0
q=0

S=[_ for _ in range(1,N+1)]
A=[]
for i in itertools.permutations(S,len(S)):
    A.append(list(i))

for j in range(N_fac):
    if P==A[j]:
        p=j
    if Q==A[j]:
        q=j

print(abs(p-q))

Solution (Python):
import itertools

n = int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))

i = 0
for x in itertools.permutations(range(1,n+1)):
  i += 1
  if list(x)==num1:
    a = i
  if list(x)==num2:
    b = i

print(abs(a-b))

Solution (Python):
from collections import deque 
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
p_que = deque()
q_que = deque()
for i in range(n):
    p_que.appendleft(p[i])
    q_que.appendleft(q[i])

def culc_num(n, que):
    li = []
    count = 0
    for i in range(n):
        li.append(i+1)
    for i in range(n):
        num = que.pop()
        index= li.index(num)
        dif = index
        for i in range(1,len(li)):
            dif*=i
        count+=dif
        li.remove(num)
    return count

print(abs(culc_num(n, q_que) - culc_num(n, p_que)))

Solution (Python):
from itertools import permutations
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))


def permutation(l: list, n: int) -> list:
    return [p for p in permutations(l, n)]

def main():
    comb = permutation([i for i in range(1, N+1)], N)
    a = comb.index(P)
    b = comb.index(Q)
    print(abs(a - b))

if __name__ == '__main__':
    main()

Solution (Python):
from itertools import permutations

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

i = 0

for x in permutations(range(1, n + 1)):
    i += 1
    if list(x) == p:
        a = i
    if list(x) == q:
        b = i

print(abs(a - b))

Solution (Python):
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
import time
from bisect import bisect_left, insort_left, bisect_right
import sys
import random
import itertools

input = sys.stdin.readline
_NUMINT_ALL = list(range(10))
_START_TIME = time.time()


def main():
    ans = solve()

    if ans is True or ans is False:
        YesNo(ans)
    elif ans is not None:
        print(ans)


def solve():
    N = iip()[0]
    P = iip()
    Q = iip()

    np = 1
    nq = 1

    for p in itertools.permutations(range(N)):
        
        for i, s in enumerate(p):
            if s+1 != P[i]:
                break
        else:
            break
        np += 1

    for q in itertools.permutations(range(N)):
        
        for i, s in enumerate(q):
            if s+1 != Q[i]:
                break
        else:
            break
        nq += 1

    
    

    return abs(np-nq)








def kiriage_warizan(a, b):
    return -(-a//b)


def iip(listed=True):  
    d = input().rstrip("\n").split()
    try:
        ret = [int(i) for i in d]
    except:
        ret = [int(i) if i in _NUMINT_ALL else i for i in d]
        if len(ret) == 1 and listed is False:
            return ret[0]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iipt(l, listed=True, num_only=True):  
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed))
    return ret


def saidai_kouyakusuu(A):  
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m

def time_debug_10percent():
    a = random.randint(0, 9)
    if a == 9:
        sys.exit()

def time_debug(t):
    time.sleep(_START_TIME + t - time.time())
    sys.exit()


def make_graph_edge_flat(N):  
    ret = []
    for i in range(N-1):
        a, b, c = iip()
        a -= 1
        b -= 1
        ret[a].append((b, c))
        ret[b].append((a, c))
    return ret


def sort_tuples(l, index):  
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  
    if index >= len(l):                      
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def sortstr(s):  
    return "".join(sorted(s))


def iip_ord(startcode="a"):  
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  
    for i in s:
        print(i)


def bitall(N):  
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        
        pass
    return ret


def inv(n, mod):  
    return power(n, mod - 2)


def power(n, p, mod_=mod):  
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


def nibutan_func(func, target, left, right, side="left"): 
    l = left
    r = right
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if func(x) == target:
            return x
        elif func(x) > target:
            r = x
        else:
            l = x

    if side == "left" or func(x) == target:
        return l
    else:
        return r


def nibutan_list(list_, target, side="left"):  
    if not isinstance(list_, list):
        list_ = list(list_)

    l = 0
    r = len(list_)
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if list_[x] == target:
            return x
        elif list_[x] > target:
            r = x
        else:
            l = x

    if side == "left" or list_[x] == target:
        return l
    else:
        return r


class UfTree():
    def __init__(self, maxnum):
        self.parent = list(range(maxnum))
        self._size = [1] * maxnum
        self.rank = [0] * maxnum

    def size(self, a):
        return self._size[self.root(a)]

    def root(self, a):
        rank = 0
        cur = a
        while True:
            if self.parent[cur] == cur:
                
                
                return cur
            else:
                self.parent[cur] = self.parent[self.parent[cur]]
                cur = self.parent[cur]
                rank += 1

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return self

        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        return self

if __name__ == "__main__":
    main()

Solution (Python):
from itertools import permutations

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

s = list(range(1, n+1))
s = list(permutations(s))

a, b = 0, 0

for i, v in enumerate(s, start=1):
	if v == p:
		a = i
	elif v == q:
		b = i
	else:
		pass

print(0) if p == q else print(abs(a - b))

Solution (Python):
N = int(input())
P = [int(i) for i in input().split(' ')]
Q = [int(i) for i in input().split(' ')]

fact = [1] * 8
for i in range(1,8):
    fact[i] = fact[i-1] * i

a = 0
remain = list(range(1,N+1))

for i , v  in enumerate(P):
    num = remain.index(v)
    remain.remove(v)
    a += num * fact[(N - i - 1)]

b = 0
remain = list(range(1,N+1))

for i , v  in enumerate(Q):
    num = remain.index(v)
    remain.remove(v)
    b += num * fact[(N - i - 1)]

print(abs(b-a))

Solution (Python):
import itertools
N = str(input())
P = ''.join(list(map(str, input().split())))
Q = ''.join(list(map(str, input().split())))
l=[]
for v in itertools.permutations(P):
    l.append(''.join(v))
print(abs(sorted(l).index(P)-sorted(l).index(Q)))

Solution (Python):
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
import itertools 
data = list(itertools.permutations([i+1 for i in range(n)]))
for i in range(len(data)):
    d = list(data[i])
    if p==d:a=i
    if q==d:b=i
print(abs(a-b))

Solution (Python):
N = int(input())
P = "".join(list(input().split()))
Q = "".join(list(input().split()))

Z = [(0,"",[0]*N)]
A = []
while Z:
    z = Z.pop(0)
    if z[0]==N:
        A.append(z[1])
        continue
    for i in range(N):
        if z[2][i]==0:
            zz = z[2][::]
            zz[i]=1
            Z.append((z[0]+1,z[1]+str(i+1),zz))
A.sort()
a,b = 0,0
for i in range(len(A)):
    if A[i]==P:
        a = i
    if A[i]==Q:
        b = i
print(abs(a-b))

Solution (Python):
import itertools
N = int(input())
L = list(itertools.permutations(list(range(1, N + 1))))
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
print(abs(L.index(P) - L.index(Q)))

Solution (Python):
N = int(input())
P = [int(i) for i in input().split(' ')]
Q = [int(i) for i in input().split(' ')]

fact = [1] * 8
for i in range(1,8):
    fact[i] = fact[i-1] * i

a = 0
remain = list(range(1,N+1))

for i , v  in enumerate(P):
    num = remain.index(v)
    remain.remove(v)
    a += num * fact[(N - i - 1)]

b = 0
remain = list(range(1,N+1))

for i , v  in enumerate(Q):
    num = remain.index(v)
    remain.remove(v)
    b += num * fact[(N - i - 1)]

print(abs(b-a))

Solution (Python):
from itertools import permutations
n = int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
for i, l in enumerate(permutations(range(1, n+1)), 1):
  if p == list(l):
    a = i
  if q == list(l):
    b = i
print(abs(a-b))

Solution (Python):
import itertools
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
f = list(map(lambda x:list(x),list(itertools.permutations([i+1 for i in range(n)],n))))
print(abs(f.index(p) - f.index(q)))

Solution (Python):
import itertools
n = int(input())
r = [i+1 for i in range(n)]
p = list(map(int,input().split()))
q = list(map(int,input().split()))
f = list(itertools.permutations(r,n))
f = list(map(lambda x:list(x),f))
print(abs(f.index(p) - f.index(q)))

Solution (Python):




from itertools import permutations

N = int(input())
P = tuple(i-1 for i in map(int, input().split()))
Q = tuple(i-1 for i in map(int, input().split()))

F = list(permutations(range(N)))

print(abs(F.index(P) - F.index(Q)))

Solution (Python):
import itertools
 
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
 
l = [i for i in range(1,n+1)] 
 
x = 0
y = 0
 
m = list(itertools.permutations(l))
 
for i in range(len(m)):
	if m[i] == p:
  		x = i+1
	if m[i] == q:
 		y = i+1
        
print(abs(x-y))

Solution (Python):

import itertools

N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))

lis=list(itertools.permutations(P))
lis.sort()


print(abs(lis.index(P)-lis.index(Q)))

Solution (Python):
import itertools

N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))

L = [i for i in range(1, N+1)]
a = 0
b = 0


L_list = list(itertools.permutations(L))

for i in range(len(L_list)):
  if list(L_list[i]) == P:
    a = i+1
  if list(L_list[i]) == Q:
    b = i+1

print(abs(a-b))

Solution (Python):
import itertools

N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))

L = [i for i in range(1, N+1)]
a = 0
b = 0


L_list = list(itertools.permutations(L))

for i in range(len(L_list)):
  if list(L_list[i]) == P:
    a = i+1

for i in range(len(L_list)):
  if list(L_list[i]) == Q:
    b = i+1



print(abs(a-b))

Solution (Python):
import itertools
def ii():return int(input())
def iim():return map(int,input().split())
def iil():return list(map(int,input().split()))
def ism():return map(str,input().split())
def isl():return list(map(str,input().split()))

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

a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))

print(abs(l.index(a)-l.index(b)))

'''
n = ii()
ans = []
def DFS(head, rest):
    if len(rest) == 0:
        print('hoge')
        ans.append(head)
        rest.append(head.pop(-1))
        return 0
    else:
        print('foo')
        head.append(rest.pop(0))
        DFS(head, rest)
        tmp = head[-1]
        head[-1] = rest[-1]
        rest[-1] = tmp


d = []
DFS(d,list(range(1,n+1)))
print(d)
'''

Solution (Python):
import itertools

N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))

A = list(itertools.permutations(range(1,N+1)))
cnt_a = 0
cnt_b = 0
for i in range(len(A)):
  if P == A[i]:
    cnt_a += i
  if Q == A[i]:
    cnt_b += i

print(abs(cnt_a - cnt_b))

Solution (Python):
import itertools
N=int(input())
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))

l=[i for i in range(1,N+1)]
for n,t in enumerate(itertools.permutations(l,N)):
    if(t==P):
        a=n
    if(t==Q):
        b=n

print(abs(a-b))

Solution (Python):
import itertools

n=int(input())

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

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

l=range(1,n+1)

a=0

b=0

cnt=0

for i in itertools.permutations(l,n):
  i=list(i)
  if i==p:
    a=cnt
  if i==q:
    b=cnt

  cnt+=1

print(abs(a-b))

Solution (Python):
import itertools
 
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))

l = list(range(1,n+1))
dic = {}

for i,j in enumerate(itertools.permutations(l)):
    dic[j] = i+1
print(abs(dic[p]-dic[q]))

Solution (Python):
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
seq = [i for i in range(1, n + 1)]

arr = list(itertools.permutations(seq))
print(abs(arr.index(p) - arr.index(q)))

Solution (Python):
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
cnt = 1
for i in itertools.permutations(range(1, n + 1), n):
    if list(i) == p:
        a = cnt
    if list(i) == q:
        b = cnt
    cnt += 1
print(abs(a - b))

Solution (Python):

import itertools
l = list(range(1, int(input()) + 1))
p = list(map(int, input().split()))
q = list(map(int, input().split()))
cnt_a = 1
cnt_b = 1
for i in itertools.permutations(l):
    if list(i) == p:
        a = cnt_a
    if list(i) == q:
        b = cnt_b
    cnt_a += 1
    cnt_b += 1
print(abs(a - b))

Solution (Python):
import itertools
n = int(input())
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
c = []
for i in range(1,n+1):
	c.append(i)

p_list = list(itertools.permutations(c))
ans = abs(p_list.index(a) - p_list.index(b))
print(ans)

Solution (Python):
N = int(input())
P = tuple(map(int, input().split()))
Q= tuple(map(int, input().split()))
L = []
for i in range(1,N+1):
    L.append(i)
import itertools
A = list(itertools.permutations(L,N))
for i in range(len(A)):
    if P == A[i]:
        a = i+1
    if Q == A[i]:
        b = i+1
print(abs(a-b))

Solution (Python):
from itertools import permutations as pe
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
l = [i for i in range(1, N+1)]
p, q = 0, 0
for i,j  in enumerate(pe(l)):
    if j==P:
        p = i+1
    if j==Q:
        q = i+1
print(abs(p-q))

Solution (Python):
from itertools import permutations

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))

a = 0
b = 0
for i, iter in enumerate(permutations(range(1, N+1))):
    if iter == P:
        a = i
    if iter == Q:
        b = i

print(abs(a-b))

Solution (Python):
from itertools import permutations

n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
for i, pi in enumerate(permutations(range(1, n+1))):
    if pi == p:
        a = i
    if pi == q:
        b = i
print(abs(a - b))

Solution (Python):
import itertools

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
U = list(itertools.permutations(range(1, N+1)))
a = U.index(P)
b = U.index(Q)
print(abs(a-b))