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):
from math import floor,ceil,sqrt,factorial,log
from collections import Counter, deque
from functools import reduce
import numpy as np
import itertools
def S(): return input()
def I(): return int(input())
def MS(): return map(str,input().split())
def MI(): return map(int,input().split())
def FLI(): return [int(i) for i in input().split()]
def LS(): return list(MS())
def LI(): return list(MI())
def LLS(): return [list(map(str, l.split() )) for l in input()]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def LLSN(n: int): return [LS() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]

n = I()

P = LI()
Q = LI()

tp = tuple(P)
tq = tuple(Q)

combination = sorted(list(itertools.permutations(P, n)))
a = 0
b = 0
for i, v in enumerate(combination):
    if v == tp:
      if a == 0:
        a = i+1

    if v == tq:
      if b == 0:
        b = i+1
    
print(np.absolute(a-b))

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

from itertools import permutations

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

ans = l.index(p) - l.index(q)
print(abs(ans))

Solution (Python):
import itertools

N = int(input())
P_list = list(map(int, input().split()))
Q_list = list(map(int, input().split()))
sort_list = sorted(P_list)
factorial_list = list(itertools.permutations(sort_list))
a = 1 + factorial_list.index(tuple(P_list))
b = 1 + factorial_list.index(tuple(Q_list))
print(abs(a-b))

Solution (Python):
import math
def difference(li):
  x=[int(i) for i in range(1,n+1)]
  l=len(li)
  sum=0
  for i in range(l):
    sum+=math.factorial(l-i-1)*(x.index(li[i]))
    x.remove(li[i])  
  return sum+1

n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
r1=difference(p)
r2=difference(q)
result=abs(r1-r2)
print(result)

Solution (Python):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
import math
nP = 1
nQ = 1
n = N-1
work = [i for i in range(1, N+1)]
for p in P:
    nP += work.index(p) * math.factorial(n)
    work.remove(p)
    n -= 1
n = N-1
work = [i for i in range(1, N+1)]
for q in Q:
    nQ += work.index(q) * math.factorial(n)
    work.remove(q)
    n -= 1
print(abs(nP-nQ))

Solution (Python):
import sys

n = int(sys.stdin.readline().rstrip())
*p, = map(int, sys.stdin.readline().split())
*q, = map(int, sys.stdin.readline().split())

factorial = [1] * (n + 1)
for i in range(n): factorial[i+1] = factorial[i] * (i + 1)

def main():
    d = 0
    a = [0] * (n + 1); b = [0] * (n + 1)
    for i in range(n - 1):
        a[p[i]] = b[q[i]] = 1
        c1 = c2 = 0
        for j in range(1, p[i]): c1 += a[j]
        for j in range(1, q[i]): c2 += b[j]
        d += ((q[i] - c2) - (p[i] - c1)) * factorial[n-(i+1)]
    print(abs(d))

if __name__ ==  '__main__':
    main()

Solution (Python):
import math
from collections import deque
import copy

n = int(input())
pL = list(input().split(" "))
qL = list(input().split(" "))

q = deque()
li = list(map(str, range(1, n + 1)))

for i in range(1, n + 1):
    q.append(str(i))

while True:
    item = q.popleft()
    if len(item) == n:
        q.appendleft(item)
        break
    for s in li:
        if not s in list(item):
            q.append(item + s)

idx = 1
pi, qi = 0, 0
while len(q) != 0:
    item = q.popleft()
    if item == "".join(pL):
        pi = idx
    if item == "".join(qL):
        qi = idx
    idx += 1

print(abs(qi - pi))

Solution (Python):
n = int(input())
aa = list(map(int, input().split()))
bb = list(map(int, input().split()))

def getcnt(aa):
    cnt = 0
    for i in range(len(aa)):
        cnt *= len(aa) - i
        cnt += aa[i] - 1
        for j in range(i+1,len(aa)):
            if aa[j] > aa[i]:
                aa[j] -= 1
    return cnt+1

print(abs(getcnt(aa) -getcnt(bb)) )

Solution (Python):
from itertools import permutations
import math

N = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
perm = list(permutations(range(1, N + 1)))
a = None
b = None

for i in range(math.factorial(N)):
    if perm[i] == tuple(p):
        a = i + 1
    if perm[i] == tuple(q):
        b = i + 1

print(abs(a - b))

Solution (Python):
import itertools
n = int(input())
a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))
arr = list(itertools.permutations(range(1,n + 1),n))
print(abs(arr.index(a) - arr.index(b)))

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

pl=list(map(int,input().split()))
ql=list(map(int,input().split()))


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

p = list(itertools.permutations(l))
p.sort()
a=p.index(tuple(pl))
b=p.index(tuple(ql))

print(abs(a-b))

Solution (Python):
import itertools

n = int(input())
pn = tuple(map(int, input().split()))
qn = tuple(map(int, input().split()))

n_list = list(range(1, n+1))
counter = 1

for i in itertools.permutations(n_list, n):
  if pn == i:
    a = counter
  if qn == i:
    b = counter
  counter += 1
  
print(abs(a-b))

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

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

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

items = [str(v) for v in range(1,N+1)]
used = [False for _ in range(N+1)]
junretu = list()

def dfs(now):
    if len(now) == N:
        junretu.append(now)
        return
    for i,v in enumerate(items):
        if used[int(v)]:
            continue
        
        used[int(v)] = True
        dfs(now+v)
        used[int(v)] = False
    return

dfs('')
sorted_junretu = sorted(list(junretu))

p_d,q_d = 0,0

for i,s in enumerate(sorted_junretu):
    if s == P:
        p_d = i
    if s == Q:
        q_d = i

print(abs(p_d-q_d))

Solution (Python):
import itertools

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


l = list(itertools.permutations(P)) 
m = sorted(l)
a = m.index(P)
b = m.index(Q)
ans = abs(a - b) 
print(ans)

Solution (Python):
from itertools import permutations
N = int(input())
ps = list(map(int, input().split()))
qs = list(map(int, input().split()))

xs = [i+1 for i in range(N)]
perms = permutations(xs,N)
cntp = cntq = 0
for i,(perm) in enumerate(perms):
    
    if list(perm) == ps: cntp = i
    if list(perm) == qs: cntq = i
print(abs(cntp-cntq))

Solution (Python):
from itertools import permutations
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

def main():
    N = int(readline())
    P = tuple([int(i) for i in readline().split()])
    Q = tuple([int(i) for i in readline().split()])

    pattern = list(permutations(range(1,N+1)))

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


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

p = list(permutations(list(range(1, N+1)), N))

a = p.index(tuple(P))
b = p.index(tuple(Q))

print(abs(a-b))

Solution (Python):
import itertools

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

pmt = list(itertools.permutations(range(1, N+1)))
pmtP = pmt.index(P)
pmtQ = pmt.index(Q)
print(abs(pmtP - pmtQ))

Solution (Python):
import itertools

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

R = list(itertools.permutations(N_))

Pflg = Qflg = False
Pcnt = Qcnt = -1
for i, r in enumerate(R):
    if P==r:
        Pflg = True
        Pcnt = i
    if Q==r:
        Qflg = True
        Qcnt = i
    if Pflg and Qflg:
        break

print(abs(Pcnt - Qcnt))

Solution (Python):
import itertools
n = int(input())
p_inputs = tuple([int(i) for i in input().split()])
q_inputs = tuple([int(i) for i in input().split()])


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

print(abs(li.index(p_inputs)-li.index(q_inputs)))

Solution (Python):
from itertools import permutations
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)
dic= sorted(list(permutations(l,n)))
r=len(dic)
dicp=0
dicq=0
for x in range(r):
    dic[x]=list(dic[x])
    if dic[x]==p:
        dicp=x+1
    if dic[x]==q:
        dicq=x+1
print(max(dicp-dicq,dicq-dicp))

Solution (Python):
from itertools import permutations
from bisect import bisect_left

n = int(input())
p = int(input().replace(" ", ""))
q = int(input().replace(" ", ""))

temp_list = [int("".join(temp)) for temp in permutations([str(x) for x in range(1, n + 1)])]
temp_list.sort()

ans = abs(bisect_left(temp_list, p) - bisect_left(temp_list, q))
print(ans)

Solution (Python):
import math
import itertools
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
lists = list(itertools.permutations(P, N))
lists.sort()
print(abs(lists.index(tuple(P)) - lists.index(tuple(Q))))

Solution (Python):










mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    import itertools
    n = int(input())
    
    p = tuple(map(int,input().split()))
    q = tuple(map(int,input().split()))
    
    num = [i + 1 for i in range(n)]
    per = list(itertools.permutations(num))
    
    print(abs(per.index(q) - per.index(p)))



if __name__ == '__main__':
  main()

Solution (Python):
from itertools import permutations
n = int(input())
a = list(permutations(range(1,n+1),n))
print(abs(a.index(tuple(map(int,input().split())))-a.index(tuple(map(int,input().split())))))

Solution (Python):
from itertools import permutations

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

for i, order in enumerate(permutations(range(1,N+1))):
    if list(order) == P:
        a = i
    if list(order) == 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()))
P=tuple(P)
Q=tuple(Q)
l=[]
R=[]
for i in range(N):
    l.append(i+1)
for i in itertools.permutations(l,N):
    R.append(i)
x=R.index(P)
y=R.index(Q)
print(abs(x-y))

Solution (Python):
N = int(input())
P = list(map(str, input().split(' ')))
Q = list(map(str, input().split(' ')))
ans = []
now = []

def CulucPermutation(array, now, level):
    if level==N:
        ans.append(''.join(now))
        
        return
    for i in range(0,N):
        if array[i] not in now:
            now += [array[i]]
            
            CulucPermutation(array, now, level+1)
            now.pop()
            
        else:
            pass

def main():
    
    n = []
    for i in range(1,N+1):
        n += [str(i)]
    
    CulucPermutation(n, now, 0)
    
    p = ''.join(P)
    q = ''.join(Q)
    print(abs(ans.index(p) - ans.index(q)))

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

a,b=0,0
A=sorted([i for i in permutations(P)])
for j,i in enumerate(A):
    i=list(i)
    if i==P:a=j+1
    if i==Q:b=j+1
print(abs(a-b))

Solution (Python):


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

a,b=0,0

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

for i in range(n-1):
    for j in range(n):
        if l[j]==p[i]:
            l.pop(j)
            break
    tmp=j
    for j in range(1,n-i):
        tmp*=j
    a+=tmp



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

for i in range(n-1):
    for j in range(n):
        if l[j]==q[i]:
            l.pop(j)
            break
    tmp=j
    for j in range(1,n-i):
        tmp*=j
    b+=tmp


        
print(abs(a-b))

Solution (Python):

import itertools


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

    p_cnt = 0
    q_cnt = 0
    i = 0
    for temp in itertools.permutations([i + 1 for i in range(n)]):
        i += 1
        if temp == p:
            p_cnt = i
        if temp == q:
            q_cnt = i

        if p_cnt != 0 and q_cnt != 0:
            break

    return abs(q_cnt - p_cnt)


if __name__ == '__main__':
    print(main())

Solution (Python):
from itertools import permutations

N = int(input())
P = "".join(input().split())
Q = "".join(input().split())
L = []
perm = permutations(range(1, N + 1), N)
for p in perm:
    s = "".join(map(str, list(p)))
    L.append(s)
L.sort()
print(abs(L.index(P) - L.index(Q)))

Solution (Python):
def q3():
    from itertools import permutations
    N = int(input())
    P = [int(i) for i in input().split()]
    Q = [int(i) for i in input().split()]

    n_list = list(range(1, N+1))
    n_perm = permutations(n_list, N)
    p_i, q_i = 0, 0
    for i, p in enumerate(n_perm):
        if P == list(p):
            p_i = i
        if Q == list(p):
            q_i = i
    print(abs(p_i - q_i))


if __name__ == '__main__':
    q3()

Solution (Python):
import math

N = int(input())
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]
sort_P = []
sort_Q = []
count_A = 1
count_B = 1
count_sum = 1

for i in range(len(P) - 1):
    x = P.pop(0)
    y = Q.pop(0)
    sort_P.append(x)
    sort_Q.append(y)
    sort_P.sort()
    sort_Q.sort()
    count_A += (x - sort_P.index(x) - 1) * math.factorial(N - 1 - i)
    count_B += (y - sort_Q.index(y) - 1) * math.factorial(N - 1 - i)

print(abs(count_A - count_B))

Solution (Python):
'''
INPUT SHORTCUTS
N, K = map(int,input().split())
N ,A,B = map(int,input().split())
string = str(input())
arr = list(map(int,input().split()))
N = int(input())
'''
from itertools import permutations 
N = int(input())
a = list(map(str,input().split()))
a = ''.join(a)
b = list(map(str,input().split()))
b = ''.join(b)
cnt=1
lena = 0
lenb = 0
inp = [ str(i) for i in range(1,N+1)]
inp = ''.join(inp)
perm = permutations(inp)
for i in list(perm):
	temp = ''.join(list(i))
	
	if temp==a:
		lena=cnt
	if temp==b:
		lenb=cnt
	cnt+=1
print(abs(lena-lenb))

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

P = it.permutations([i for i in range(1,n+1)],n)

a = 0
b = 0
cnt = 1
if p==q:
  print(0)
  exit()
for i in P:
  if p==i:
    a = cnt
    cnt +=1
  elif q==i :
    b = cnt
    cnt +=1
  else:
    cnt +=1
ans = abs(a-b)
print(ans)

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):
from itertools import permutations

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

R = [i for i in range(1, N+1)]

li = []
for i in permutations(R, N):
    li.append(list(i))

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

Solution (Python):
import itertools
n = int(input())
p =tuple(map(int,input().split()))
q =tuple(map(int,input().split()))
l = list(itertools.permutations(range(1,n+1),n))
l.sort()
for k,t in enumerate(l):
  if t==p:
    px = k+1
  if t==q:
    qx = k+1
print(abs(px-qx))

Solution (Python):
from itertools import permutations as par
n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
i=0
for q in par([i+1 for i in range(n)]):
    q=list(q)
    if q==A: A=i
    if q==B: B=i
    i+=1
print(abs(A-B))

Solution (Python):
import itertools

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

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


anss = list(itertools.permutations(nli, n))


ans = abs(anss.index(ps) - anss.index(qs))
print(ans)

Solution (Python):


import itertools

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

     num = [x + 1 for x in range(n)]
     p_list = list(map(list, (itertools.permutations(num))))
     
     idx_p = p_list.index(p)
     idx_q = p_list.index(q)

     print(abs(idx_p - idx_q))

if __name__ == "__main__":
    main()

Solution (Python):
import itertools

n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
l3 = sorted(l1)
l = list("")
for i in itertools.permutations(l3):
    l.append(list(i))
print(abs(l.index(l1) - l.index(l2)))

Solution (Python):
from itertools import permutations

N = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
A = [i for i in range(1, N+1)]
cnt = 0
op = -1
oq = -1
for j in permutations(A):
  cnt += 1
  if(j == p):
    op = cnt
  if(j == q):
    oq = cnt
    
print(abs(op-oq))

Solution (Python):
import math
import itertools

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

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

junretu = list(itertools.permutations(n_list))
sorted(junretu)
idx_p = 0
idx_q = 0
for i in range(math.factorial(n)):
    if list(junretu[i]) == p:
        idx_p = i
    if list(junretu[i]) == q:
        idx_q = i
    elif idx_p != 0 and idx_q != 0:
        break

print(abs(idx_q - idx_p))

Solution (Python):
import itertools


def main():
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    l = [i for i in range(1, n + 1)]
    mp = {}
    for v in itertools.permutations(l, n):
        mp[v] = len(mp)
    print(abs(mp[p] - mp[q]))


if __name__ == '__main__':
    main()

Solution (Python):
import itertools

num = int(input())
c = [i + 1 for i in range(num)]

a = tuple([int(i) for i in input().split(" ")])
b = tuple([int(i) for i in input().split(" ")])

a_num = 0
b_num = 0

for num,i in enumerate(itertools.permutations(c)):
    if a == i:
        a_num = num
    if b == i:
        b_num = num

print(abs(a_num - b_num))

Solution (Python):
def main():
    n = int(input())
    p = tuple(int(i) for i in input().split())
    q = tuple(int(i) for i in input().split())
    from itertools import permutations 
    a = [i for i in range(1, n+1)]
    o1 = -1
    o2 = -1
    cnt = 0
    for i in permutations(a):
      cnt += 1
      if i == p:
          o1 = cnt
      if i == q:
          o2 = cnt
      ans = abs(o1-o2)
    print(ans)
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 j in permutations(range(1,n+1)):
  i+=1
  if list(j)==p:
      p=i
  if list(j)==q:
      q=i
print(abs(p-q))

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

def da(a,n):
    x = [1,2,3,4,5,6,7,8]
    y = x[:n]
    count = 0
    for v in itertools.permutations(y):
        w = list(v)
        if w == a:
            return count
        
        count += 1
print(abs(da(q,n)-da(p,n)))

Solution (Python):
import sys
n=int(input())
l=[i for i in range(1,n+1)]
a=tuple(map(int,sys.stdin.readline().strip().split()))
b=tuple(map(int,sys.stdin.readline().strip().split()))
import itertools
List=[]
for i in itertools.permutations(l):
  List+=[i]
print(abs(List.index(a)-List.index(b)))

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

jyunretu=[]
for i in range(1,n+1):
    jyunretu.append(str(i))
p = itertools.permutations(jyunretu, n)

jyunretulist=[]
for i in p:
    jyunretulist.append(list(i))
    
p=input().split()
q=input().split()

for i ,youso in enumerate(jyunretulist):
    if youso==p:
        a=i
    if youso==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()))

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

Solution (Python):
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
num_list = list((itertools.permutations(range(1,n+1))))
print(abs(num_list.index(p)-num_list.index(q)))

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


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

print(abs(a-b))

Solution (Python):
from itertools import permutations

n = int(input())
p = tuple(int(i) - 1 for i in input().split())
q = tuple(int(i) - 1 for i in input().split())
per = list(permutations(range(n)))
print(abs(per.index(p) - per.index(q)))

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

l = range(1, n+1)
count = 0
for elem in itertools.permutations(l, n):
    count += 1
    if elem == p:
        p_count = count
    if elem == q:
        q_count = count

print(abs(p_count-q_count))

Solution (Python):
import math
from functools import reduce
import itertools

def input1():
	return int(input())


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


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





N=input1()
P=input_array()
Q=input_array()

nums=list(itertools.permutations(range(1,N+1)))


a=nums.index(tuple(P))
b=nums.index(tuple(Q))
print(abs(a-b))

Solution (Python):
import itertools

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

x = list(itertools.permutations(R,N))
print(abs(x.index(P)-x.index(Q)))

Solution (Python):

import sys
from collections import Counter
from itertools import permutations, combinations
from fractions import gcd
from math import ceil, floor
sys.setrecursionlimit(10 ** 6)

def input():
    return sys.stdin.readline()[:-1]

def main():
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    l = permutations(list(range(1, n+1)))
    if p == q:
        print(0)
    else:
        for idx, item in enumerate(l):
            if item == p:
                idp = idx
            elif item == q:
                idq = idx
        print(abs(idp - idq))

if __name__ == '__main__':
    main()

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

Solution (Python):
import itertools
n = int(input())
pl = list(map(int,input().split()))
ql = list(map(int,input().split()))
li = [i for i in range(1,n+1)]
it = list(itertools.permutations(li, n))
a = 0
b = 0
for i,t in enumerate(it):
    
    if list(t) == pl:
        a = i
    if list(t) == ql:
        b = i
print(abs(a-b))

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

import itertools

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

cnt = 0
t = []
for i in itertools.permutations(a, n):
    cnt += 1
    if list(i) == p:
        t.append(cnt)
    if list(i) == q:
        t.append(cnt)
print(abs(t[0] - t[1]))

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
 
N = INT()
P = LIST()
Q = LIST()
 
def hoge(A, m):
  c = -1
  for j in range(m):
    if A[j] == 1  :
      c += 1   
  return c
 
def Numth(R, N):
  ORDER = [1]*N
  c = 0
  for i in range(N-1):
    c += hoge(ORDER, R[i]) *factorial(N-i-1)
    ORDER[R[i]-1] = 0 
  return c+1
 
print(abs(Numth(P, N)-Numth(Q, N)))

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
 
N = INT()
P = LIST()
Q = LIST()
 
def Numth(R, N):
  ORDER = [1]*N
  c = 0
  for i in range(N-1):
    c += (ORDER[:R[i]].count(1) - 1) *factorial(N-i-1)
    ORDER[R[i]-1] = 0 
  return c+1

print(abs(Numth(P, N)-Numth(Q, N)))

Solution (Python):
N=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
def fac(N):
	if N==0:
		return 1
	else:
		return(fac(N-1)*N)
def count(a):
	co=0
	for i in range(len(a)):
		b=sorted(a)
		for j in range(len(a)):
			if b[j]==a[0]:
				p=j
		co+=fac(len(a)-1)*p
		a=a[1:]
	return co
print(abs(count(p)-count(q)))

Solution (Python):
import math
n=int(input())
p=[int(c) for c in input().split()]
q=[int(c) for c in input().split()]

l=0
num=list(range(1,n+1))
for i in range(n):
  l+=(num.index(p[i]))*(math.factorial(n-i-1))
  num.remove(p[i])
  
a=l+1

num=list(range(1,n+1))
r=0
for i in range(n):
  r+=(num.index(q[i]))*(math.factorial(n-i-1))
  num.remove(q[i])
  
b=r+1

print(str(abs(a-b)))

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
P = LIST()
Q = LIST()

def hoge(A, m):
  c = -1
  for j in range(m):
    if A[j] == 1  :
      c += 1   
  return c

def Numth(R, N):
  ORDER = [1]*N
  c = 0
  for i in range(N-1):
    order = sum(ORDER[:i+1])
    c += hoge(ORDER, R[i]) *factorial(N-i-1)
    ORDER[R[i]-1] = 0 
  return c+1

print(abs(Numth(P, N)-Numth(Q, N)))

Solution (Python):


import itertools

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

a = list(range(1,N+1))
b = itertools.permutations(a)

ans1 = 1
ans2 = 1

for i in b:
    if i == P:
        break
    ans1 += 1

b = itertools.permutations(a)

for i in b:
    if i == Q:
        break
    ans2 += 1

print(abs(ans1-ans2))

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

Solution (Python):
import math

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

num = list(range(1,n+1))
p_id = 0
q_id = 0

for i in range(n):
    p_id += num.index(p[i]) * math.factorial(len(num)-1)
    num.remove(p[i])

num = list(range(1,n+1))

for i in range(n):
    q_id += num.index(q[i]) * math.factorial(len(num)-1)
    num.remove(q[i])

print(abs(p_id-q_id))

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

ans_p = 0
defa = [_ for _ in range(1,n+1)]
for i,x in enumerate(p):
    index = defa.index(x)
    ans_p += math.factorial(n-i-1)*len(defa[:index])
    defa.remove(x)
    
ans_q = 0
defa = [_ for _ in range(1,n+1)]
for i,x in enumerate(q):
    index = defa.index(x)
    ans_q += math.factorial(n-i-1)*len(defa[:index])
    defa.remove(x)
    
print(abs(ans_p-ans_q))

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

l = list(itertools.permutations(range(1, n+1)))
dict = {}

index = 1
for i in l:
    dict[i] = index
    index += 1

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

print(abs(dict[tuple(p)] - dict[tuple(q)]))

Solution (Python):
import itertools
n = int(input())
p = [int(i)-1 for i in input().split()]
q = [int(i)-1 for i in input().split()]
m = sorted(p)
a = 0
b = 0
cnt = 1

for i in itertools.permutations(m, n):
  
  if list(i) == p:
    a += cnt
  if list(i) == q:
    b += cnt
  if a!=0 and b!=0:
    break
  else:
    cnt += 1
    
print(abs(a-b))

Solution (Python):

import sys
import numpy as np

import itertools

def solve(N: int, P: "List[int]", Q: "List[int]"):
    num = [i for i in range(1,N+1)]
    c=1
    a=b=0
    for p in itertools.permutations(num):
        if list(p)==P:
            a=c
        if list(p)==Q:
            b=c
        c+=1

    print(abs(a-b))

    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))  
    P = [int(next(tokens)) for _ in range(N)]  
    Q = [int(next(tokens)) for _ in range(N)]  
    solve(N, P, Q)

if __name__ == '__main__':
    main()

Solution (Python):

if False:
    K,X=map(int,input().split())
    print('Yes' if 500*K>=X else 'No')


if False:
    N=int(input())
    S=input()
    print(S.count('ABC'))


if True:
    import itertools
    N=int(input())
    dic=list(itertools.permutations(list(range(1,N+1))))
    
    P=tuple(int(i) for i in input().split())
    Q=tuple(int(i) for i in input().split())

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

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