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):
def permutation(lst): 
  
    
    if len(lst) == 0: 
        return [] 
  
    
    
    if len(lst) == 1: 
        return [lst] 
  
    
    
  
    l = [] 
  
    
    for i in range(len(lst)): 
       m = lst[i] 
  
       
       
       remLst = lst[:i] + lst[i+1:] 
  
       
       
       for p in permutation(remLst): 
           l.append([m] + p) 
    return l 

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

NN = list(range(1,int(N)+1))
P = permutation(NN)

xx = P.index(x)
yy = P.index(y)
print(abs(xx-yy))

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

fact = []
f = 1
for i in range(1,N+1):
    fact.append(f)
    f *= i
fact.reverse()

def dicNum(L):
    ans = 0
    block = N
    l = [i+1 for i in range(N)]
    for i in range(N-1):
        inde = 0
        for j in l:
            if L[i]==j:
                l.pop(inde)
                break
            else:
                inde += 1
        
        ans += fact[i]*inde
    return ans
    
print(abs(dicNum(P)-dicNum(Q)))

Solution (Python):
import itertools

n = int(input())

p = tuple(int(i) for i in input().split())
q = tuple(int(i) for i in input().split())

idx = 1
for i in itertools.permutations(range(1, n + 1)):
    if i == p:
        pi = idx
    if i == q:
        qi = idx
    idx += 1

print(abs(pi - qi))

Solution (Python):
import itertools
def main():
    N = int(input())
    A = list(map(int , input().split()))
    B = list(map(int , input().split()))
    
    
    
    
    list_N = list(range(1,N+1))
    
    
    
    
    n1 = 0
    n2 = 0
    count_n = 0
    for i in itertools.permutations(list_N) :
        if A == B :
            print ("0")
            break
        list_i = list(i)
        
        
        count_n = count_n + 1
        if A == list_i :
            n1 = count_n
        elif B == list_i :
            n2 = count_n
        
    
    
    if A != B :
        print (str(abs(n1 - n2)))


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

perm = list(permutations(range(1,N+1),N))
print(abs(perm.index(P)- perm.index(Q)))

Solution (Python):
import math

def function(items, item):
  num = sorted(items)
  num.reverse()
  return num.index(item)+1
   
n = int(input())
p = input().split()
p = [int(_) for _ in p]
q = input().split()
q = [int(_) for _ in q]

items = []
for i in range(n-1):
  items.append(math.factorial(n-i-1))

p_temp = []
for i in range(len(p)):
  p_temp.append((len(p[i:])+1) - function(p[i:], p[i]))

q_temp = []
for i in range(len(q)):
  q_temp.append((len(q[i:])+1) - function(q[i:], q[i]))


p_num = 0
for i in range(len(p)-1):
  t = p_temp[i]-1
  p_num += t*items[i]
  
q_num = 0
for i in range(len(q)-1):
  t = q_temp[i]-1
  q_num += t*items[i]

print(abs(p_num - q_num))

Solution (Python):
N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
a = 0
b = 0
used_a = [True for i in range(N)]
used_b = [True for i in range(N)]
def cal(x,used):
    n = 0
    for i in range(N):
        if used[i] and x > (i+1):
            n += 1
        else:
            pass
    ret = 1
    p = sum(used) - 1
    while True :
        if p == 0 :
            break
        else:
            ret *= p
            p -= 1
    return ret * n

for i in range(N-1):
    a += cal(P[i],used_a)
    used_a[P[i]-1] = False
    b += cal(Q[i],used_b)
    used_b[Q[i]-1] = False
print(abs(a-b))

Solution (Python):



import pdb
import sys
import math
F = sys.stdin

N = int(F.readline().rstrip())
P = list(map(int,F.readline().rstrip().split()))
Q = list(map(int,F.readline().rstrip().split()))
p_used = []
q_used = []
p_ans = 0
q_ans = 0

for n in range(N):
    p_used.append(P[n])
    for i in range(P[n] - 1):
        if i+1 in p_used:
            continue
        p_ans += math.factorial(N - n - 1)

    q_used.append(Q[n])
    for i in range(Q[n] - 1):
        if i+1 in q_used:
            continue
        q_ans += math.factorial(N - n - 1)


ans = abs(p_ans - q_ans)

print(ans)

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

Solution (Python):
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
def sn(a,n):
  c=0
  for i in a:
    if i<n:
      c+=1
  return c
def comb(n):
  k=1
  if n<=1:
    return 1
  for i in range(1,n+1):
    k=k*i
  return k
def numberorder(a,n):
  s=set({})
  for i in range(1,n+1):
    s=s|{i}
  c=0
  for p in range(n):
    c+=(sn(s,a[p]))*comb(n-1-p)
    s=s-{a[p]}
  return c
P_num=numberorder(P,N)
Q_num=numberorder(Q,N)
print(abs(P_num-Q_num))

Solution (Python):
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
import math
def top(A):
    s = 0
    for i in range(0,len(A)):
        if A[i] > A[0]:
            s = s + 1
    return s
def count(A):
    t = 0
    for i in range(1,N):
        t = t + top(A) * math.factorial(N-i)
        A.pop(0)
    return t
a = abs(count(P)-count(Q))
print(a)

Solution (Python):
import math
n=int(input())
plis=list(map(int,input().split()))
qlis=list(map(int,input().split()))
acounter=0
bcounter=0
pdic=[]
qdic=[]
for i in range(1,n+1):
	pdic.append(i)
	qdic.append(i)
for i in range(n):
	a=int((math.factorial(n-i)/(n-i))*(pdic.index(plis[i])))
	acounter+=a
	pdic.remove(plis[i])
	b=int((math.factorial(n-i)/(n-i))*(qdic.index(qlis[i])))
	bcounter+=b
	qdic.remove(qlis[i])
print(abs((acounter+1)-(bcounter+1)))

Solution (Python):
import math

N = int(input())
P_str = input().split()
P = [int(p) for p in P_str]
Q_str = input().split()
Q = [int(q) for q in Q_str]

pnumber = [m for m in range(1, N+1)]
qnumber = [m for m in range(1, N+1)]

pnum = 1
qnum = 1

for i in range(N):
    pnum += pnumber.index(P[i])*math.factorial(N-i-1)
    pnumber.remove(P[i])
    
for i in range(N):
    qnum += qnumber.index(Q[i])*math.factorial(N-i-1)
    qnumber.remove(Q[i])

print(abs(pnum-qnum))

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

import itertools

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

zyu = itertools.permutations(l, n)

for t, child in enumerate(zyu):
    p_flag = True
    q_flag = True
    for check_idx in range(0, n):
        if list(child)[check_idx] == p[check_idx]:
            pass
        else:
            p_flag = False
            break

    for check_idx in range(0, n):    
        if list(child)[check_idx] == q[check_idx]:
            pass
        else:
            q_flag = False
            break

    if p_flag:
        p_idx = t+1

    if q_flag:
        q_idx = t+1



print(abs(q_idx-p_idx))

Solution (Python):
import itertools
n = int(input())
a = tuple(input().split())
b = tuple(input().split())

num = list(str(i) for i in range(1,n+1))
iters = list(itertools.permutations(num))

for i in range(len(iters)):
  if a == iters[i]:
    A = i
  elif b == iters[i]:
    B = i

if a == b:
  print(0)
else:
  print(abs(A-B))

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

Pj = 0

for i in range(N-1):
  k = i + 1  
  Pj = Pj + sum(1 for x in P[k:] if P[i] > x) * math.factorial(N-1-i)

Pj += 1

Qj = 0

for i in range(N-1):
  k = i + 1  
  Qj = Qj + sum(1 for x in Q[k:] if Q[i] > x) * math.factorial(N-1-i)

Qj += 1

print(abs(Pj - Qj))

Solution (Python):
import math
import random
from operator import itemgetter
import re
import sys
from itertools import accumulate
from collections import defaultdict
from collections import deque
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import functools
N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
ans = 0
for i in range(N):
    ans += (Q[i]-P[i])*math.factorial(N-1-i)
    for j in range(N-1-i):
        if Q[i+j+1] >Q[i]:
             Q[i+j+1] -= 1
        if P[i+j+1] >P[i]:
             P[i+j+1] -= 1
print(abs(ans))

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

import itertools
tmp = [i for i in range(1,N+1)]

tmp2 = itertools.permutations(tmp)
a,b = 0,0
for n,j in enumerate(tmp2):
  
  if list(j)==P:
    a = n+1
    
  if list(j)==Q:
    b = n+1
    
res=abs(a-b)

print(res)

Solution (Python):


import math

N = int(input())

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

n = list(range(1, N + 1))
a = 1
for i in range(len(P) - 1):
	a += math.factorial(N - i - 1) * (n.index(P[i]))
	n.remove(P[i])

n = list(range(1, N + 1))
b = 1
for i in range(len(Q) - 1):
	b += math.factorial(N - i - 1) * (n.index(Q[i]))
	n.remove(Q[i])

print(abs(a - b))

Solution (Python):
import math
from bisect import bisect_left
N=int(input())
P=[int(i) for i in input().split()]
Q=[int(i) for i in input().split()]
a=1
b=1
for i,n in enumerate([m for m in range(1,N+1)]):
    if min(P[i:])<P[i]:
        a+=bisect_left(sorted(P[i:]),P[i])*math.factorial(N-i-1)
    if min(Q[i:])<Q[i]:
        b+=bisect_left(sorted(Q[i:]),Q[i])*math.factorial(N-i-1)
print(abs(a-b))

Solution (Python):
def kaijo(m):
    kotae=1
    for i in range(1,m+1):
        kotae*=i
    return kotae

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

for i in range(n):
    p[i]-=1
    q[i]-=1

pnum=0
qnum=0

pki=[[]for i in range(n)]
qki=[[]for i in range(n)]

for i in range(1,n):
    for j in range(i):
        pki[i].append(p[j])
        qki[i].append(q[j])

for i in range(n):
    kai=n-i-1
    count=0
    for j in range(p[i]):
        if(not j in pki[i]):
            count+=1
    pnum+=count*kaijo(kai)

    count=0
    for j in range(q[i]):
        if(not j in qki[i]):
            count+=1
    qnum+=count*kaijo(kai)

ans=pnum-qnum
ans=max(ans,-1*ans)

print(ans)

Solution (Python):


import itertools

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

a = list(range(1,n+1,1))
count = 1

res1 = 0
res2 = 0

temp = []

for i in itertools.permutations(a):
    for j in range(n):
        temp.append(i[j])
    if temp == p and (res1 == 0):
        res1 = count
    if temp == q and (res2 == 0):
        res2 = count
    count += 1
    temp = []

print(abs(res1-res2))

Solution (Python):


def iim():
    return map(int, input().rstrip().split())

from math import factorial
def calc(a):
    N = len(a)
    aa = []
    bk = [factorial(i) for i in range(N-1, 0, -1)]

    bl = [0] * N
    for i in range(N-1, 0, -1):
        x = a[i]
        for j in range(i):
            if a[j] > x:
                bl[j] += 1

    n = 0
    for i in range(0, N-1):
        n += bk[i] * bl[i]

    return n

def resolve():
    N = int(input())
    P = list(iim())
    Q = list(iim())

    print(abs(calc(P) - calc(Q)))

if __name__ == "__main__":
    resolve()

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

import itertools

s = []

for j in range(N):
    s.append(j + 1)

n_P = 0
n_Q = 0

list_seed = list(itertools.permutations(s, N))
list_seed = [list(list_seed[i]) for i in range(len(list_seed))]

for i in range(len(list_seed)):
    if list_seed[i] == P:
        n_P = i + 1
    if list_seed[i] == Q:
        n_Q = i + 1

print(abs(n_P - n_Q))

Solution (Python):
import itertools
import math

n = int(input())
p = list(map(str,input().split()))
q = list(map(str,input().split()))
lst = []
for i in range(n):
    lst.append(str(i+1))
lst_perm = list(itertools.permutations(lst))
a=0
b=0
for i in range(math.factorial(n)):
    if ("".join(p))==("".join(q)):
        if ("".join(p))==("".join(lst_perm[i])):
            a=i
            b=i
    else:
        if ("".join(p))==("".join(lst_perm[i])):
            a = i
        elif ("".join(q))==("".join(lst_perm[i])):
            b = i
print(abs(a-b))

Solution (Python):
import sys
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)))

ip = a.index(P)
iq = a.index(Q)

if ip-iq >= 0:
  print(ip-iq)
else:
  print(iq-ip)

Solution (Python):
A = input()
a = int(A)
B = input()
C = input()
res1 = tuple()
res2 = tuple()
from itertools import permutations 
l = list(permutations(range(1, a+1))) 
res1 = tuple(map(int, B.split(' ')))
res2 = tuple(map(int, C.split(' ')))
d = l.index(res1)
e = l.index(res2)
print(abs(d-e))

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

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

for i,e in enumerate(tank):
    if p == e:
        a = i
    if q == e:
        b = i
    
print(abs(a-b))

Solution (Python):
import itertools

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

seq = itertools.permutations(range(1,N+1))
listseq = list(seq)
tupleA = tuple(A)
tupleB = tuple(B)

indexA = listseq.index(tupleA) + 1
indexB = listseq.index(tupleB) + 1

ans = abs(indexA - indexB)

print(ans)

Solution (Python):
import itertools

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

l = []
for i in range(N):
  l.append(i+1)
ll = list(itertools.permutations(l))

PP = ll.index(P)
QQ = ll.index(Q)

print(abs(PP - QQ))

Solution (Python):
import math

def CountOrder(n, a):
    used = []
    order = 0
    for i in range(len(a)):
        nn = a[i] - 1
        for u in used:
            if u < a[i]:
                nn -= 1
        used.append(a[i])

        order += nn * math.factorial(n - 1 - i)

    return order + 1
        
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

print(abs(CountOrder(n, a) - CountOrder(n, b)))

Solution (Python):
import itertools

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

l = list(range(1, N+1))
p = [list(v) for v in itertools.permutations(l, len(l))]

a = p.index(P)+1
b = p.index(Q)+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))
ll=list(itertools.permutations(l,n))
pp=ll.index(p)
qq=ll.index(q)
a=pp-qq
if a<0:
  a=a*(-1)
print(str(a))

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

import math

Listp = []
for i in range(1,N):
    countp = 0
    for j in range(0,i):
        if P[j] <= P[i]:
            countp = countp + 1
        else:
            countp = countp
    Listp.append(countp)

Listq = []
for i in range(1,N):
    countq = 0
    for j in range(0,i):
        if Q[j] <= Q[i]:
            countq = countq + 1
    Listq.append(countq)


ansp = (P[0]-1)*math.factorial(N-1)
for i in range(1,N):
    ansp = ansp + (P[i]-Listp[i-1]-1)*math.factorial(N-i-1)
    
ansq = (Q[0]-1)*math.factorial(N-1)
for i in range(1,N):
    ansq = ansq + (Q[i]-Listq[i-1]-1)*math.factorial(N-i-1)
    
print(abs(ansp-ansq))

Solution (Python):
import math


def value(x_list, kaijo):

    num_list = list(range(len(x_list)+1))

    result = 1
    count = len(x_list)
    for x in x_list:
        kaijo /= count
        count -= 1
        target_value = num_list[x] - 1
        result += target_value * kaijo

        new_list = [0]*(len(x_list)+1)

        for i, num in enumerate(num_list):
            if num > target_value:
                new_list[i] = num-1
            else:
                new_list[i] = num

        num_list = new_list

    return int(result)


N = int(input())
p_list = list(map(int, input().split()))
q_list = list(map(int, input().split()))

kaijo = math.factorial(N)

p_value = value(p_list, kaijo)
q_value = value(q_list, kaijo)
print(abs(p_value-q_value))

Solution (Python):
import itertools

n = int(input())
p_list = list(map(int, input().split()))
q_list = list(map(int, input().split()))
p_list = tuple(p_list)
q_list = tuple(q_list)
n_list = list(range(1, n+1))

a_list = list(itertools.permutations(n_list))
a = a_list.index(p_list)
b = a_list.index(q_list)

print(abs(a-b))

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

for i in range(n-1):
  c=0
  d=0
  for j in range(i+1,n):
    if p[i]>p[j]:
      c+=1
    if q[i]>q[j]:
      d+=1
  a+=c*math.factorial(n-i-1)
  b+=d*math.factorial(n-i-1)
print(abs(a-b))

Solution (Python):
import itertools

N = int(input())
P_ar = list(map(int,input().split()))
Q_ar = list(map(int,input().split()))

List = list(map(list,list(itertools.permutations(range(N)))))

for i in range(N):
  P_ar[i]-=1
  Q_ar[i]-=1

a=-1
b=-1

for i in range(len(List)):
  if List[i]==P_ar:
    a=i
    break

for i in range(len(List)):
  if List[i]==Q_ar:
    b=i
    break

print(abs(a-b))

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

import math
import itertools
import numpy as np

s = [x for x in range(N + 1)][1:N+1]
strs = [str(s) for s in s]

i = 1
for v in itertools.permutations(strs):
    i = i + 1
    V = [int(v) for v in v]
    if V == P:
        a = i
    if V == 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()))
A = [9] * N
B = [9] * N
Pcount = 0
Qcount = 0
Pnum = 1
Qnum = 1
Ans = 0

for i in range(N-1):
  for j in range(N):
    if P[i] > A[j]:
      Pcount = Pcount + 1
  
  for k in range(N):
    if Q[i] > B[k]:
      Qcount = Qcount + 1
    
  Pnum = Pnum + math.factorial(N - i - 1) * (P[i] - 1 - Pcount)
  Qnum = Qnum + math.factorial(N - i - 1) * (Q[i] - 1 - Qcount)
  
  A[i] = P[i]
  B[i] = Q[i]
  Pcount = 0
  Qcount = 0


Ans = abs(Pnum - Qnum)


print(Ans)

Solution (Python):
import numpy as np
import math

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

def _get_order(N, v, i):
  order=np.argsort(v[i:])
  return list(order).index(0) * math.factorial(len(order)-1)

def get_order(N, v):
  each_order=list(map(lambda i: _get_order(N, v, i), range(N)))
  return each_order
a = sum(get_order(N, P))
b = sum(get_order(N, Q))
print(abs(a-b))

Solution (Python):
import itertools

def main():
    N = int(input())
    
    P = list(map(int, input().split()))
    Q = list(map(int, input().split()))
    
    combi = list(itertools.permutations(range(1, N+1)))
    
    pi = 0
    qi = 0
    for i in range(len(combi)):
        if list(combi[i]) == P:
            pi = i + 1
        if list(combi[i]) == Q:
            qi = i + 1
            
            
    print(abs(qi - pi))
    
main()

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


  
  
    
  
    
      
    



  
  

per=list(itertools.permutations(l))

for i in range(len(per)):
  
  if per[i]==p:
    a=i
  if per[i]==q:
    b=i
print(abs(a-b))

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

def ans(l, con):
  if con == n - 1:
    return 0
  k = bisect.bisect_right(sorted(l[con:]),l[con])
  return k*math.factorial(n - 1 - con) + ans(l, con + 1)
print(abs(ans(p, 0)-ans(q,0)))

Solution (Python):
import collections as c
ip = lambda : map(int, input().split())

N = int(input())
p = list(ip())
q = list(ip())

d = {0:1}
for i in range(1,N):
    d[i] = d[i-1]*i

ansp = 0
ansq = 0
lp = list(range(1,N+1))
lq = list(range(1,N+1))
for i in range(N-1):
    ansp += d[N-1-i]*(lp.index(p[i]))
    ansq += d[N-1-i]*(lq.index(q[i]))
    lp.pop(lp.index(p[i]))
    lq.pop(lq.index(q[i]))
    
print(abs(ansp-ansq))

Solution (Python):
import itertools

N=int(input())
P=list((map(int,input().split())))
Q=list((map(int,input().split())))
cnt=1
for u in itertools.permutations(range(1,N+1)):
    for i in range(N):
        if u[i]==P[i]:
            continue
        else:
            break
    else:
        a=cnt
    for i in range(N):
        if u[i]==Q[i]:
            continue
        else:
            break
    else:
        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()))

for i, d in enumerate(itertools.permutations(range(1, N+1), N)):
    if d == P:
        a = i
    if d == Q:
        b = i

print(abs(a-b))

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

fact = [1]
for i in range(1, n):
  fact.append(fact[-1] * i)
  
check = [True] * (n+1)
check[0] = False

a = 1
for i, p in enumerate(map(int, input().split())):
  check[p] = False
  a += sum(check[:p]) * fact[n-i-1]
  
check = [True] * (n+1)
check[0] = False

b = 1
for i, p in enumerate(map(int, input().split())):
  check[p] = False
  b += sum(check[:p]) * fact[n-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()))

for i, aaa in enumerate(itertools.permutations(range(1,N+1),N)):
    if P == list(aaa):
        num_P = i + 1

    if Q == list(aaa):
        num_Q = i + 1

print(abs(num_P-num_Q))

Solution (Python):
import math

def n_check(N,P):
  N_list = list(range(1,N+1))
  n = 0
  for i in P:
    n += (N_list.index(i))*(math.factorial(len(N_list)-1))
    N_list.remove(i)
  return n

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

p_n = n_check(N,P) + 1
q_n = n_check(N,Q) + 1

print(abs(p_n - q_n))

Solution (Python):
import itertools
n=int(input())
p=tuple([int(i) for i in input().split()])
q=tuple([int(i) for i in input().split()])
x=list(itertools.permutations(range(1,n+1)))
nc=len(x)

for i in range(nc):
  if x[i]==p:
    pn=i
    
for j in range(nc):
  if x[j]==q:
    qn=j


print(abs(pn-qn))

Solution (Python):
import itertools

N = int(input())
P = int(input().replace(' ', ''))
Q = int(input().replace(' ', ''))
s = [i for i in range(1, N + 1)]
l = list(itertools.permutations(s))
j = []
for i in range(len(l)):
  t = map(str,l[i])
  j.append(int(''.join(t)))

nl = sorted(j) 
a = 0
b = 0

for i in range(len(nl)):
  if nl[i] == P:
    a = i + 1
  if nl[i] == Q:
    b = i + 1
    
print(abs(a -b))

Solution (Python):
import itertools
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
permute = list(map(list,list(itertools.permutations(range(1,n+1)))))


index_a = permute.index(a)
index_b = permute.index(b)
print(abs(index_a-index_b))

Solution (Python):
import itertools
import math
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
L = list(map(list,list(itertools.permutations(list(i for i in range(1,N+1)),N))))
a = L.index(P)
b = L.index(Q)
print(abs(a-b))

Solution (Python):
def heapPermutation(a, size, n,all_perms): 
	if (size == 1): 
		all_perms.append(a[:])
		return

	for i in range(size): 
		heapPermutation(a,size-1,n,all_perms)
		if size&1: 
			a[0], a[size-1] = a[size-1],a[0] 
		else: 
			a[i], a[size-1] = a[size-1],a[i] 
		

def main():
    n = int(input())
    p = list(map(int,input().split()))
    q = list(map(int,input().split()))
    arr = [i for i in range(1,n+1)]
    all_perms = []
    heapPermutation(arr,n,n,all_perms)
    all_perms.sort()
    a = -1
    b = -1
    for i in range(len(all_perms)):
        if all_perms[i] == p:
            a = i
        elif all_perms[i] == q:
            b = i

    if a == -1 or b == -1:
        print(0)
        return

    print(abs(a-b))


main()

Solution (Python):
import math

N = int(input())
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]
a, b = 0, 0
P_l = [0] * N
Q_l = [0] * N
for i in range(N-1):
  P_l[P[i]-1] = 1
  a += (P[i] - 1 - sum(P_l[:P[i]-1])) * math.factorial(N-i-1)
  Q_l[Q[i]-1] = 1
  b += (Q[i] - 1 - sum(Q_l[:Q[i]-1])) * math.factorial(N-i-1)
print(abs(a-b))

Solution (Python):
from math import factorial

n = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]

def f(X):
    c = 0
    a = [i+1 for i in range(n)]
    for i in range(n):
        a.sort()
        
        if X[i]!=min(a):
            c += factorial(n-i-1)*(a.index(X[i]))
        del a[a.index(X[i])]
    return c+1

print(abs(f(P)-f(Q)))

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

M = []
for i in range(1,N+1):
    M.append(i)

L = list(itertools.permutations(M))

cnt = 0
pc = 0
qc = 0
for i in range(len(L)):
    cnt+=1
    K = list(L[i])
    if K==P:
        pc = cnt
    if K==Q:
        qc = cnt

print(abs(pc-qc))

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


def order(X):
    lst_n = list(range(1, N + 1))
    res = 0
    for i in range(N - 1):
        j = 0
        while True:
            if X[i] == lst_n[j]:
                res = (res + j) * (N - i - 1)
                lst_n = lst_n[:j] + lst_n[j + 1:]
                break
            j += 1
    return res + 1


print(abs(order(P) - order(Q)))

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()

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

    ls = [0] * 9
    ls[0] = 1
    for i in range(N):
        ls[i+1] = ls[i] * (i+1)

    p_sum = 0
    q_sum = 0
    p_ls = [1,2,3,4,5,6,7,8]
    q_ls = [1,2,3,4,5,6,7,8]
    for j in range(N):
        p_sum += p_ls.index(P[j]) * ls[N-j-1]
        p_ls.remove(P[j])
        q_sum += q_ls.index(Q[j]) * ls[N-j-1]
        q_ls.remove(Q[j])
    
    print(abs(p_sum - q_sum))

if __name__ == '__main__':
    main()

Solution (Python):
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
n_list = [i for i in range(1,N+1)]
n_perm = sorted(list(itertools.permutations(n_list, N)))
a = 0
b = 0

for i in range(len(n_perm)):
    if list(n_perm[i]) == P:
        a = i
        break

for k in range(len(n_perm)):
    if list(n_perm[k]) == Q:
        b = k
        break
        
print(abs(a-b))

Solution (Python):
import math
import itertools

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
new_p = sorted(p)
new_q = sorted(q)
check = 0
roop = math.factorial(n)

list_p = []
list_q = []
for i in itertools.permutations(new_p):
    list_p.append(i)
for i in itertools.permutations(new_q):
    list_q.append(i)

check = 0
for i in range(roop):
    if list_p[i] == tuple(p):
        a = i
        check += 1
    if list_q[i] == tuple(q):
        b = i
        check += 1
    if check == 2:
        break

print(abs(a-b))

Solution (Python):
import math
from itertools import permutations


bi = 0
ci = 0

a = int(input())
b = list(input().split())
c = list(input().split())

bstr = ''.join(b)
cstr = ''.join(c)

blist = sorted([''.join(p) for p in permutations(b)])
clist = sorted([''.join(p) for p in permutations(c)])

for i in range(math.factorial(a)):
	if bstr == blist[i]:
		bi = i
	if cstr == clist[i]:
		ci = i
print(abs(bi - ci))

Solution (Python):
import itertools

N = int(input())
PER = []
for i in range(N):
    PER.append(i+1)

P = list(map(int,input().split()))
Q = list(map(int,input().split()))
a = 0
b = 0
tmp = 1

for x in itertools.permutations(PER):
     
    flag_a = 0
    flag_b = 0
 
    for i in range(N):
        if x[i] == P[i]:
            flag_a += 1   
        if x[i] == Q[i]:
            flag_b += 1
    if flag_b == N:
        b = tmp
    if flag_a == N:
        a = tmp
    tmp += 1

ans = a - b
if ans < 0:
    ans = - ans

print(ans)

Solution (Python):
import bisect
from math import factorial


n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
p_c = [i for i in range(1, n+1)]
q_c = [i for i in range(1, n+1)]
ans_p = 1
ans_q = 1
for i in range(n-1):
    p_c.pop(p_c.index(p[i]))
    q_c.pop(q_c.index(q[i]))
    ans_p += (bisect.bisect_left(p_c, p[i])) * factorial(n - i - 1)
    ans_q += (bisect.bisect_left(q_c, q[i])) * factorial(n - i - 1)
print(abs(ans_p - ans_q))

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

Solution (Python):
import math

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

P1=P
P2=[0]*n
for i in range(n):
    P1=[p-1 if p>=P1[i] else p for p in P1]
    P2[i]=P1[i]
A=0
for j in range(n):
    A+=math.factorial(n-j-1)*P2[j]
    
Q1=Q
Q2=[0]*n
for i in range(n):
    Q1=[q-1 if q>=Q1[i] else q for q in Q1]
    Q2[i]=Q1[i]
B=0
for j in range(n):
    B+=math.factorial(n-j-1)*Q2[j]

print(abs(A-B))

Solution (Python):

import itertools
N = int(input())
in_p = input().split()
in_q = input().split()
P = [0 for i in range(N)]
Q = [0 for i in range(N)]
for i in range(N):
    P[i] = int(in_p[i])
    Q[i] = int(in_q[i])
R = list(itertools.permutations(sorted(P)))
idx_P = 0
idx_Q = 0
for i in range(len(R)):
    if list(R[i]) == P:
        idx_P = i+1
    if list(R[i]) == Q:
        idx_Q = i+1
    if idx_P != 0 and idx_Q != 0:
        break
print(abs(idx_P-idx_Q))

Solution (Python):
import itertools

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

x = itertools.permutations(list(range(1, n+1)), n)
pnum = 0
qnum = 0
for index, xx in enumerate(x):
  if(list(xx) == p):
    pnum = index
  if(list(xx) == q):
    qnum = index
    
print(abs(pnum - qnum))

Solution (Python):

import sys
import math
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
ans = [0,0]
for pq in range(2):
    l = q if pq % 2 else p
    
    for i in range(n-1):
        
        k = sorted(l[i:]).index(l[i])
        ans[pq] += k*math.factorial(n-i-1)
print(abs(ans[0]-ans[1]))