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):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))

lists = []

def dfs(li, nums):
    if len(nums) == 0:
        lists.append(li)
        return
    for num in nums:
        new = li[::]
        new.append(num)
        new_nums = nums[::]
        new_nums.remove(num)
        dfs(new, new_nums)
dfs([], [i for i in range(1, N+1)])

p_idx = 0
q_idx = 0

for i in range(len(lists)):
    li = lists[i]
    if P == li:
        p_idx = i
    if Q == li:
        q_idx = i
print(abs(p_idx - q_idx))

Solution (Python):
n = int(input())
list_p = list(map(int,input().split()))
list_q = list(map(int,input().split()))
list1 = sorted(list_p)
list2 = sorted(list_q)

import math

lista=[]
listb=[]

for i in range(n-1):
    lista.append((list1.index(list_p[i]))*math.factorial(n-i-1))
    listb.append((list2.index(list_q[i]))*math.factorial(n-i-1))
    list1.remove(list_p[i])
    list2.remove(list_q[i])
    
print(abs(sum(lista)-sum(listb)))

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

fac = [0] * 8
fac[1] = 1
for i in range(2, N):
    fac[i] = i * fac[i - 1]

a = 0
l = list(range(1, N + 1))
for i in range(N):
    a += l.index(P[i]) * fac[len(l) - 1]
    l.remove(P[i])

b = 0
l = list(range(1, N + 1))
for i in range(N):
    b += l.index(Q[i]) * fac[len(l) - 1]
    l.remove(Q[i])

print(abs(a - b))

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

Solution (Python):
import itertools

N = int(input())
P = ''.join(input().split())
Q = ''.join(input().split())

n_l = [str(i) for i in range(1,N+1)]
N_lists = [''.join(i) for i in itertools.permutations(n_l)]

index_P = N_lists.index(P)
index_Q = N_lists.index(Q)

ans = abs(index_P - index_Q)

print(ans)

Solution (Python):
import itertools
N = int(input())
P,Q = [list(map(int,input().split())) for i in range(2)]
dictionary = sorted(itertools.permutations(P,N))

print(abs(dictionary.index(tuple(P))-dictionary.index(tuple(Q))))

Solution (Python):
import math

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

def f(A):
  l = list(range(1,N+1,1))
  a = 0
  for i in range(N):
    a += math.factorial(N-1-i) * (l.index(A[i])-1)
    del l[l.index(A[i])]
  return a

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

Solution (Python):
import itertools
import math
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
juretu=list(range(1,N+1))
so = math.factorial(N)
p=[]
for v in itertools.permutations(juretu, N):
  p.append(list(v))

P_v = [False,0]
Q_v = [False,0]
for i,v in enumerate(p):
  if P == v:
    P_v = [True,i+1]
  if Q == v:
    Q_v = [True,i+1]
  if P_v[0] and Q_v[0]:
    print(abs(P_v[1] - Q_v[1]))
    break

Solution (Python):
import itertools as it

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

L=[int(i) for i in range(1,N+1)]
A=[]
for v in it.permutations(L):
    A.append(v)

a=0
for i in range(len(A)):
    flag=True
    a=a+1
    for j in range(N):
        if A[i][j]!=P[j]:
            flag=False
            break
    if flag:
        break
b=0
for i in range(len(A)):
    flag=True
    b=b+1
    for j in range(N):
        if A[i][j]!=Q[j]:
            flag=False
            break
    if flag:
        break

print(abs(a-b))

Solution (Python):
import itertools


def main():
    n = input()
    b = input().split()
    c = input().split()

    b_comb = sorted(list(itertools.permutations(b)))
    c_comb = sorted(list(itertools.permutations(c)))
    for i in range(len(b_comb)):
        if b_comb[i] == tuple(b):
            p = i + 1
            break
    for i in range(len(c_comb)):
        if c_comb[i] == tuple(c):
            q = i + 1
            break 
    print(abs(p - q))


if __name__ == "__main__":
    main()

Solution (Python):
import itertools


def main():
    n = input()
    b = input().split()
    c = input().split()

    b_comb = sorted(list(itertools.permutations(b)))
    c_comb = sorted(list(itertools.permutations(c)))
    for i in range(len(b_comb)):
        if b_comb[i] == tuple(b):
            p = i + 1
            break
    for i in range(len(c_comb)):
        if c_comb[i] == tuple(c):
            q = i + 1
            break 
    print(abs(p - q))


if __name__ == "__main__":
    main()

Solution (Python):
import itertools

n = int(input())
a = [i+1 for i in range(n)]
p = list(map(int,input().split()))
q = list(map(int,input().split()))

r = list(itertools.permutations(a,len(a)))
r.sort()

for i in range(len(r)):
    if list(r[i]) == p:
        x = i
    if list(r[i]) == q:
        y = i
        
print(abs(x-y))

Solution (Python):
import itertools
import math

n=int(input())
lis=[i for i in range(1,n+1)]
P_lis=itertools.permutations(lis)
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))

P=list(P_lis)
P=sorted(P)



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

Solution (Python):



import sys


def input():
    return sys.stdin.readline()


def decide_position(num_list:list, n):

    if n == 2:
        if num_list[0] < num_list[1]:
            return 1
        else:
            return 2
    else:
        first_num = num_list[0]
        sorted_num_list = sorted(num_list)
        rank_in_p = sorted_num_list.index(first_num)
        n_kaizyou = 1
        for i in range(n-1, 0, -1):
            n_kaizyou *= i

        position = rank_in_p * n_kaizyou
        num_list.remove(first_num)
        position += decide_position(num_list, n-1)

        return position



def resolve():
    n = int(input())
    p_list = list(map(int, input().split()))
    q_list = list(map(int, input().split()))

    p_rank = decide_position(p_list, n)
    q_rank = decide_position(q_list, n)

    ans_rank = abs(p_rank - q_rank)

    print(ans_rank)






if __name__ == "__main__":
    resolve()

Solution (Python):
import itertools

N = int(input())
X = list(itertools.permutations(range(1,N+1), N))

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

print(abs(X.index(tuple(P))-X.index(tuple(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 math import factorial
from itertools import permutations
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))

pi = 0
qi = 0
for i, l in enumerate(list(permutations(list(range(1, n+1))))):
    l = list(l)
    if p == l:
        pi = i
    if q == l:
        qi = i
print(abs(qi - pi))

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

Solution (Python):

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

P = int("".join(P.split(" ")))
Q = int("".join(Q.split(" ")))

X = []
for i in itertools.permutations(range(1, N+1)):
    x = list(map(str, i))
    y = int("".join(x))
    X.append(y)

a = X.index(P)
b = X.index(Q)

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, v in enumerate(itertools.permutations(range(1,n+1))):
    if p==v:
        s=i
    if q==v:
        t=i
print(abs(s-t))

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

from itertools import permutations
dict_num=[]
for i in permutations(range(1,n+1)):
    dict_num.append(i)

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

Solution (Python):
from itertools import permutations

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

n = list(permutations(list(range(1, N+1))))
for i in range(len(n)):
    if  list(n[i]) == P:
        p = i+1
    if list(n[i]) == Q:
        q = i+1
print(abs(p-q))

Solution (Python):
from itertools import permutations as perm


def inpl():
    return tuple(map(int, input().split()))


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

for i, p in enumerate(perm([j+1 for j in range(N)])):
    if p == P:
        pi = i
    if p == Q:
        qi = i
print(abs(pi-qi))

Solution (Python):
import math

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

def f(perm, ord):
    n = len(perm)
    if n == 2:
        if perm == ord:
            return 1
        else:
            return 2
    else:
        i = ord.index(perm[0])
        ord.pop(i)
        return math.factorial(n-1)*i + f(perm[1:], ord)

print(abs(f(Q, [i+1 for i in range(N)]) - f(P, [i+1 for i in range(N)])))

Solution (Python):
import math
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
cnt1 = 0
cnt2 = 0
for i in range(n-1):
  cnt = 0
  for j in range(i+1,n):
    if p[i] > p[j]:
      cnt += 1
  cnt1 += cnt*math.factorial(n-(i+1))

for i in range(n-1):
  cnt = 0
  for j in range(i+1,n):
    if q[i] > q[j]:
      cnt += 1
  cnt2 += cnt*math.factorial(n-(i+1))

print(abs(cnt1 - cnt2))

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

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

l = [str(i) for i in range(1,n+1)]
p_list = list(itertools.permutations(l,len(l)))

p_str = [str(i) for i in p]
q_str = [str(i) for i in q]

a = p_list.index(tuple(p_str))
b = p_list.index(tuple(q_str))

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

iter = [i + 1 for i in range(N)]
map = {pattern: i for i, pattern in enumerate(permutations(iter, N))}
print(abs(map[P] - map[Q]))

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

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


import itertools

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

l=list(itertools.permutations(seq))
l.sort()

p=tuple(pl)
q=tuple(ql)

a=l.index(p)
b=l.index(q)
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()))

Pe = permutations(range(1,N+1),N)
a = b = 0

for i,p in enumerate(Pe):
    if P == p: a = i
    if Q == p: b = i
print(abs(a-b))

Solution (Python):
import math

N = int(input())
Pi = list(map(int,input().split()))
Qi = list(map(int,input().split()))

a = 0
b = 0

numcheck = [1 for i in range(N)]
numcheck[Pi[0]-1] = 0
a = math.factorial(N-1)*(Pi[0]-1) 
for n in range(1,N):
  num = Pi[n]
  numcheck[num-1] = 0
  a = a + math.factorial(N-1-n)*sum(numcheck[:num])
a = a + 1

numcheck = [1 for i in range(N)]
numcheck[Qi[0]-1] = 0
b = math.factorial(N-1)*(Qi[0]-1) 
for n in range(1,N):
  num = Qi[n]
  numcheck[num-1] = 0
  b = b + math.factorial(N-1-n)*sum(numcheck[:num])
b = b + 1

print(abs(a-b))

Solution (Python):
import itertools

N = int(input())
inlst = []

for _ in range(2):
    inlst.append(list(map(int, input().split())))

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

ab = []
for i, v in enumerate(inlst):
    ab.append(per.index(tuple(v)) + 1)

a, b = ab
print(abs(a - b))

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

from itertools import permutations
ss = []
for s in permutations(range(1, n + 1)):
    ss.append(s)
ss = sorted(ss)
for k, s in enumerate(ss):
    if list(s) == p:
        a = k
    if list(s) == q:
        b = k

print(abs(a - b))

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

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

from itertools import permutations
Perm = permutations(range(1,N+1),N)
a = 0
b = 0
for i,p in enumerate(Perm):
    if P == p: a = i
    if Q == p: b = i
print(abs(a-b))

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

from itertools import permutations
asc = list(range(1, N+1))

xp, xq = -1, -1
for i, arr in enumerate(permutations(asc)):
  
  if arr == P:
    xp = i
  if arr == Q:
    xq = i
  if xp > -1 and xq > -1:
    break
ans = abs(xp - xq)
print(ans)

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

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

nums = list(itertools.permutations(List))

a = nums.index(P)
b = nums.index(Q)

print(abs(a-b))

Solution (Python):
n = int(input())
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
l = tuple(x+1 for x in range(n))
c,d = 0,0
cnt = 0
from itertools import permutations
for k in permutations(l):
    cnt += 1
    if a ==k:
        c = cnt
    if b ==k:
        d = cnt
print(abs(c-d))

Solution (Python):
n = int(input())
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
l = tuple(x+1 for x in range(n))

c,d = 0,0
cnt = 0
from itertools import permutations
for k in permutations(l):
    
    cnt += 1
    if a ==k:
        c = cnt
    if b ==k:
        d = cnt
print(abs(c-d))

Solution (Python):
n=int(input())
a=tuple(map(lambda x:int(x)-1,input().split()))
b=tuple(map(lambda x:int(x)-1,input().split()))

import itertools as it
pe=list(it.permutations(range(n),n))

x,y=0,0
for ind,i in enumerate(pe):
    if i==a:
        x=ind
    if i==b:
        y=ind
print(abs(x-y))

Solution (Python):
import itertools

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

cnt = 0
a, b = 0, 0
perms = itertools.permutations(range(1, N+1))
for perm in perms:
  cnt += 1
  
  is_P = True
  for i in range(N):
    if perm[i] != P[i]:
      is_P = False
      break
  if is_P:
    a = cnt
  
  is_Q = True
  for i in range(N):
    if perm[i] != Q[i]:
      is_Q = False
      break
  if is_Q:
    b = cnt
print(abs(a-b))

Solution (Python):

import sys
import itertools

def solve(N: int, P: "List[int]", Q: "List[int]"):
    a = 0
    b = 0
    for i, v in enumerate(itertools.permutations(range(1, N+1))):
        flagp = True
        flagq = True
        for j in range(N):
            if v[j] != P[j]:
                flagp = False
            if v[j] != Q[j]:
                flagq = False
        if flagp:
            a = i+1
        if flagq:
            b = i+1
    print(abs(b-a))
    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):
import math
import itertools
N=int(input())
Plist=tuple(map(str,input().split()))
Qlist=tuple(map(str,input().split()))


s_number=""

for i in range(1,N+1):
    s_number+=str(i)
    



j=0


for i in itertools.permutations(s_number):
    
    
    
    if i==Plist:
        a=j
    j+=1
    

j=0

for i in itertools.permutations(s_number):
    
    
    
    if i==Qlist:
        b=j
    j+=1
    
print(abs(a-b))

Solution (Python):
import itertools

n = int(input())

array = [i for i in range(1, n + 1)]
gen_array = itertools.permutations(array, n)

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

idx = 1
for lis in gen_array:
    if list(lis) == a:
        num_a = idx
    if list(lis) == b:
        num_b = idx
    idx += 1

print(abs(num_a - num_b))

Solution (Python):
import itertools

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

perms = itertools.permutations(range(1, n + 1))

for idx, perm in enumerate(perms):
    perm_l = list(perm)
    if ps == perm_l:
        a = idx + 1
    if qs == perm_l:
        b = idx + 1

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

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

Solution (Python):
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
for i, a in enumerate(itertools.permutations(range(1, 1+N))):
    if a == P:
        p = i
    if a == Q:
        q = i
        
print(abs(p-q))

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

permutations = list(itertools.permutations(range(1, N+1)))
p = permutations.index(P)
q = permutations.index(Q)

ans = abs(p - q)
print(ans)

Solution (Python):
import itertools

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


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

a=perm.index(tuple(P))+1

b=perm.index(tuple(Q))+1
print(abs(a-b))

Solution (Python):
import itertools
l = []
p_num = 0
q_num = 0
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
for i in range(1,n+1):
    l.append(i)
cnt = 0
for i in itertools.permutations(l,n):
    cnt += 1
    if i == p:
        p_num = cnt
    if i == q:
        q_num = cnt
        
print(abs(p_num - q_num))

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

a=set()
b=set()

ans=0

for i in range(n):
    ans+=(p[i] - len([j for j in a if j < p[i]])) * math.factorial(n-i-1)
    a.add(p[i])
    ans-=(q[i] - len([j for j in b if j < q[i]])) * math.factorial(n-i-1)
    b.add(q[i])

print(abs(ans))

Solution (Python):
import itertools

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

list_range = list(range(1,n+1))
pattern_list = list(itertools.permutations(list_range, n))
pattern_list.sort()
ans = [0] * 2
for i in range(len(pattern_list)):
  if p == q:
    break
  elif p == list(pattern_list[i]):
    ans[0] = i + 1
  elif q == list(pattern_list[i]):
    ans[1] = i + 1
print(abs(ans[0] - ans[1]))

Solution (Python):
import itertools

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

list_perm = list(itertools.permutations([i+1 for i in range(N)]))

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

Solution (Python):
import itertools


n_int = int(input())


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

p_int = int("".join(map(str, p_int_list)))


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

q_int = int("".join(map(str, q_int_list)))


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

p_cnt = 0
q_cnt = 0

for perm_arr in itertools.permutations(n_list, n_int):

    perm_int = int("".join(map(str, perm_arr)))

    
    if perm_int <= p_int :
        p_cnt += 1

    if perm_int <= q_int :
        q_cnt += 1

    
    if  perm_int > p_int \
    and perm_int > q_int :
        break

print(abs(p_cnt - q_cnt))

Solution (Python):
import itertools
n = int(input())
pis = tuple([int(pi) for pi in input().split()])
qis = tuple([int(qi) for qi in input().split()])
perms = list(itertools.permutations(range(1,n+1)))

pn = -1
qn = -1
for p in perms:
  if pis == p:
    pn = perms.index(pis)
    
  if qis == p:
    qn = perms.index(qis)
    
  if pn > -1 and qn > -1:
    break
print(abs(pn - qn))

Solution (Python):
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
cp = 0
cq = 0
def kai(a):
    if a <= 1:
        return 1
    else:
        return a*kai(a-1)
for i in range(n):
    cp += (p[i]-1)*kai(n-i-1)
    cq += (q[i]-1)*kai(n-i-1)
    for j in range(n):
        if p[j] > p[i]:
            p[j] -= 1
        if q[j] > q[i]:
            q[j] -= 1
print(abs(cp-cq))

Solution (Python):
N = int(input())
P = input().replace(" ","")
Q = input().replace(" ","")

def add_up(string, left):
  string_set = set()
  if len(left) == 0:
    return {string}
  
  for number in left:
    string_set |= add_up(string+str(number), left-{number})
  return string_set

l = sorted(list(add_up("",set([i+1 for i in range(N)]))))
print(abs(l.index(Q)-l.index(P)))

Solution (Python):
import math

N = int(input())
P = input().split(' ')
sorted_P = sorted(P)
P_num = 0
Q = input().split(' ')
sorted_Q = sorted(Q)
Q_num = 0
for i in range(len(P) - 1):
    P_num += sorted_P.index(P[i]) * math.factorial(N - i - 1)
    sorted_P.pop(sorted_P.index(P[i]))
for j in range(len(Q) - 1):
    Q_num += sorted_Q.index(Q[j]) * math.factorial(N - j - 1)
    sorted_Q.pop(sorted_Q.index(Q[j]))
print(abs(P_num - Q_num))

Solution (Python):
import itertools

n=int(input())
p=list(input().split())
q=list(input().split())
l=[]
for v in itertools.permutations(p,n):
    l.append(list(v))
    
l=sorted(l)
p_val=0
q_val=0
m=0
for i in l:
    if i==p:
        p_val=m
    if i==q:
        q_val=m
    m+=1

print(abs(p_val-q_val))

Solution (Python):
import itertools

n=int(input())
p=list(input().split())
q=list(input().split())
l=[]
for v in itertools.permutations(p,n):
    l.append(list(v))
    
l=sorted(l)
p_val=0
q_val=0
m=0
for i in l:
    if i==p:
        p_val=m
    if i==q:
        q_val=m
    m+=1

print(abs(p_val-q_val))

Solution (Python):
from itertools import permutations
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
i = a = b = 0
for x in permutations(range(1, N+1), N):
  i += 1
  if x == P:
    a = i
  if x == 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()))
v = P[:]
v.sort()
p = tuple(P)
q = tuple(Q)
ans_a = 0
ans_b = 0
if p == q:
    print(0)
else:
    for i, l in enumerate(itertools.permutations(v)):
        if p == l:
            ans_a = i + 1
        elif q == l:
            ans_b = i + 1
    print(abs(ans_a - ans_b))

Solution (Python):
from __future__ import print_function

import sys

import re
import array
import copy
import functools
import operator

import math
import string
import fractions
from fractions import Fraction
from fractions import gcd



import collections
import itertools
import bisect

import random
import time

import heapq
from heapq import heappush
from heapq import heappop
from heapq import heappushpop
from heapq import heapify
from heapq import heapreplace
from queue import PriorityQueue as pq
from queue import Queue

from itertools import accumulate

from collections import deque
from collections import Counter

from operator import mul
from functools import reduce

input = sys.stdin.readline


def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)
    return


def lcm(n, m):
    return int(n * m / gcd(n, m))


def coprimize(p, q):
    common = fractions.gcd(p, q)
    return (p // common, q // common)


def combinations_count(n, r):
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom


def main():
    n = int(input().strip())
    a = tuple(map(int, input().strip().split()))
    b = tuple(map(int, input().strip().split()))
    l = tuple([i+1 for i in range(n)])

    n_a = 0
    n_b = 0
    for (seq, i) in zip((itertools.permutations(l)), [i for i in range(math.factorial(n))]):
        if seq == a:
            n_a = i
        if seq == b:
            n_b = i
    print(abs(n_a - n_b))


if __name__ == '__main__':
    main()

Solution (Python):
import itertools

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

if P == Q:
    print(0)
else:
    l = []
    for i in range(1, N+1):
        l.append(i)

    t = tuple(l)
    p = 0
    q = 0
    for i, v in enumerate(itertools.permutations(t)):
        if P == v:
            p = i+1
        elif Q == v:
            q = i+1
    print(abs(p - q))

Solution (Python):

import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
ans = 0
j = 0
for i in itertools.permutations(range(1, n+1)):
    j += 1
    if p == i: ans += j
    if q == i: ans -= j
print(abs(ans))

Solution (Python):
import itertools

n = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
p1 = ""
for i in p:
    p1 += str(i)

q1 = ""
for i in q:
    q1 += str(i)


a = list(map(list, itertools.permutations(p, n)))
a.sort()
b = []

for i in a:
    g = ""
    for j in i:
        g += str(j)
    b.append(g)

print(abs((b.index(p1)+1) - (b.index(q1)+1)))

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

Solution (Python):
import itertools

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

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

for i, c in enumerate(CombinationN):
    if c == P:
        a = i
    if c == Q:
        b = i

print(abs(a-b))

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

c = 0
for s in itertools.permutations(range(1, n+1), n):
    c += 1
    if s == p:
        a = c
    if s == q:
        b = c

ans = abs(a - b)
print(ans)

Solution (Python):

import math
import itertools
n = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]

tmp = [i+1 for i in range(n)]
tmp2 = list(itertools.permutations(tmp))
for i in range(len(tmp2)):
    flag1 = True
    flag2 = True
    for j in range(len(p)):
        if tmp2[i][j] != p[j]:
            flag1 = False
        if tmp2[i][j] != q[j]:
            flag2 = False
    if flag1:
        a = i + 1
    if flag2:
        b = i + 1
print(abs(a-b))

Solution (Python):
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, acos, atan, asin
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
def input(): return sys.stdin.readline().strip()
def STR(): return input()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
sys.setrecursionlimit(10 ** 9)
inf = sys.maxsize
mod = 10 ** 9 + 7

n = INT()
p = LIST()
q = LIST()
l = list(permutations(range(1, n + 1), n))
l.sort()
a = 0
b = 0
for i in range(len(l)):
    flagp = True
    flagq = True
    for j in range(n):
        if l[i][j] != p[j]:
            flagp = False
        if l[i][j] != q[j]:
            flagq = False
    if flagp:
        a = i
    if flagq:
        b = i
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()))
np,nq=0,0
for i,V in enumerate(permutations(range(1,N+1))):
    tmp=list(V)
    if all(p==v for p,v in zip(P,V)):
        np=i
    if all(q==v for q,v in zip(Q,V)):
        nq=i
print(abs(np-nq))

Solution (Python):

from itertools import permutations

N = int(input().strip())
pat_P = tuple(map(int, input().rstrip().split()))
pat_Q = tuple(map(int, input().rstrip().split()))


perm_list = [ pat for pat in permutations(range(1,N+1))]

a = perm_list.index(pat_P) + 1
b = perm_list.index(pat_Q) + 1
print(abs(a-b))

Solution (Python):

from itertools import permutations

N = int(input().strip())
pat_P = [ "".join( input().rstrip().split() )][0]
pat_Q = [ "".join( input().rstrip().split() )][0]


perm_list = [ "".join( map(str, pat) ) for pat in permutations(range(1,N+1))]
perm_list.sort()

a = perm_list.index(pat_P) + 1
b = perm_list.index(pat_Q) + 1
print(abs(a-b))

Solution (Python):
import copy


def count_order(l, r, i):
    global a
    if r == []:
        a.append(i)

    if not l:
        return 1

    sum = 0
    for x in l:
        ll = copy.copy(l)
        rr = copy.copy(r)
        if r is not None and r[0] == x:
            rr.pop(0)
        else:
            rr = None
        ll.remove(x)
        sum += count_order(ll, rr, sum + i)

    return sum


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

count_order(list(range(1, n + 1)), p, 0)
count_order(list(range(1, n + 1)), q, 0)
print(abs(a[0] - a[1]))

Solution (Python):
import itertools

n = int(input())

al = [int(x) for x in input().split()]
bl = [int(x) for x in input().split()]
l = [int(x) for x in range(1, n+1)]

a, b, flag, i = 0, 0, 0, 0

for v in itertools.permutations(l):
    i += 1
    lv = list(v)
    if al == lv:
        a = i
        flag += 1
    if bl == lv:
        b = i
        flag += 1
    if flag == 2:
        break

print(abs(a-b))

Solution (Python):
import itertools
import math
N = int(input())
P_tuple = tuple(map(int, input().split()))
Q_tuple = tuple(map(int, input().split()))

for index, p in zip(range(math.factorial(N)), itertools.permutations(range(1, N + 1))):
    if p == P_tuple:
        a = index + 1
    if p == Q_tuple:
        b = index + 1

print(abs(a - b))

Solution (Python):
import itertools
import math
N = int(input())
P = tuple(map(int,input().split(" ")))
Q = tuple(map(int,input().split(" ")))
Nk = math.factorial(N)
per = list(itertools.permutations(range(1,N+1)))
for i in range(Nk):
    if P == per[i]:
        p = i
for j in range(Nk):
    if Q == per[j]:
        q = j
print(abs(p-q))

Solution (Python):
import math

N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
P_count = 0
Q_count = 0
for i in range(N - 1):
    P_count += (P[i] - 1) * math.factorial(N - 1 - i)
    Q_count += (Q[i] - 1) * math.factorial(N - 1 - i)
    for j in range(i + 1, N - 1):
        if P[j] > P[i]:
            P[j] -= 1
        if Q[j] > Q[i]:
            Q[j] -= 1
result = abs(P_count - Q_count)
print(result)