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):
mod = 10**9+7
import sys
from collections import Counter, defaultdict, deque
from itertools import product, permutations, combinations, combinations_with_replacement
from itertools import accumulate
from operator import itemgetter
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from math import ceil,floor
from copy import deepcopy
from heapq import heappop,heappush,heapify
import heapq







sys.setrecursionlimit(10 ** 6)

int1 = lambda x: int(x) - 1


p2D = lambda x: print(*x, sep="\n")

def II(): return int(sys.stdin.readline())

def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())




def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LI(): return list(map(lambda x:int(x), sys.stdin.readline().split()))
def HI(): return list(map(lambda x:int(x)*(-1), sys.stdin.readline().split()))



n = II()
p = tuple(MI())
q = tuple(MI())

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

Solution (Python):
import itertools

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

seq=[i for i in range(1, n+1)]
permutation=list(map(list, itertools.permutations(seq)))
p_index=permutation.index(p_list)
q_index=permutation.index(q_list)

print(abs(p_index-q_index))

Solution (Python):






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





import itertools





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

Solution (Python):
N = int(input())
P = [int(j) for j in input().split()]
Q = [int(j) for j in input().split()]
from itertools import permutations
ALL = [list(e) for e in list(permutations(list(set(P))))]
print(abs(ALL.index(P)-ALL.index(Q)))

Solution (Python):
import math
import itertools

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

for i in range(1, N+1, 1):
  R.append(i)

l = list(itertools.permutations(R))

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

Solution (Python):
import itertools

n = int(input())
ppp = tuple(map(int, input().split()))
qqq = tuple(map(int, input().split()))

p = None
q = None
for i, aaa in enumerate(itertools.permutations(range(1, n+1))):
  if aaa == ppp:
    p = i
  if aaa == qqq:
    q = i

if p > q:
  print(p - q)
else:
  print(q - p)

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

Solution (Python):
import itertools

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


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

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

print(abs(a - b))

Solution (Python):
from itertools import permutations

N = int(input())
nums = ''.join([str(i) for i in range(1, N+1)])
P = list(map(str, input().split()))
Q = list(map(str, input().split()))
P = ''.join(P)
Q = ''.join(Q)


ref_list = list(permutations(nums, N))
for i in range(len(ref_list)):
  s = ''.join(ref_list[i])
  if s == P:
    a = i+1
  elif s == Q:
    b = i+1
    
if P == Q:
  print(0)
else:
  print(abs(a - b))

Solution (Python):
import itertools

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

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

ans = abs(jyun_list.index(P)-jyun_list.index(Q))

print(ans)

Solution (Python):
from itertools import permutations
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
p_, q_ = 0, 0
for i, o in enumerate(permutations(range(1, n + 1), n)):
    if p == o:
        p_ = i + 1
    if q == o:
        q_ = i + 1
print(abs(p_ - q_))

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

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

n_list = list(itertools.permutations(l, n))


ans1 = 0
ans2 = 0

for i in range(len(n_list)):
    if n_list[i] == p:
        ans1 = i
    if n_list[i] == q:
        ans2 = i

print(abs(ans1-ans2))

Solution (Python):
import itertools

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

ANS=[]
NUM=[]
i=0
while i<N:
    NUM.append(i+1)
    i+=1


j=0
for i in itertools.permutations(NUM):
    ANS.append(i)
    if list(i)==P:
        PANS=j+1
    if list(i)==Q:
        QANS=j+1
    j+=1

print(abs(PANS-QANS))

Solution (Python):
from itertools import permutations
N = int(input())
P, Q = tuple(map(int, input().split())), tuple(map(int, input().split()))
a, b = 0, 0
for i, perm in enumerate(permutations(range(1, N + 1), N)):
    if perm == P:
        a = i + 1
    if perm == Q:
        b = i + 1
    if all((a, b)):
        print(abs(a - b))
        break

Solution (Python):
import itertools

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

p_index = -1
q_index = -1
combs = itertools.permutations(range(1, n + 1), n)
for index, each in enumerate(combs):
    if all(P[i] == each[i] for i in range(n)):
        p_index = index

    if all(Q[i] == each[i] for i in range(n)):
        q_index = index
print(abs(p_index - q_index))

Solution (Python):
from math import factorial

def ABC150C(s):
    n = len(s)
    ans = 0
    while n > 1:
        o = s[0]
        ans += (o - 1) * factorial(n - 1)
        s.pop(0)
        n = len(s)
        if n == 0:
            break
        s = [i if i < o else i - 1 for i in s]
    return ans

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
print(abs(ABC150C(p) - ABC150C(q)))

Solution (Python):
n = int(input())
p_l = list(map(int,input().split()))
q_l = list(map(int,input().split()))

kaijo = 1
for i in range(1,n+1):
    kaijo *= i

a = 0
for i in range(n):
    kaijo //= (n-i)
    a += (p_l[i]-1)*kaijo
    for j in range(n):
        if p_l[j] > p_l[i]:
            p_l[j] -= 1

kaijo = 1
for i in range(1,n+1):
    kaijo *= i

b = 0
for i in range(n):
    kaijo //= (n-i)
    b += (q_l[i]-1)*kaijo
    for j in range(n):
        if q_l[j] > q_l[i]:
            q_l[j] -= 1

print(abs(a-b))

Solution (Python):
import sys
import itertools

input = sys.stdin.readline

def main():
    a = b = 0
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    d = [1,2,3,4,5,6,7,8,9]

    prm = list(itertools.permutations(d[:n], n))

    a = prm.index(p) + 1
    b = prm.index(q) + 1

    print(abs(a-b))

if __name__ == '__main__':
    main()

Solution (Python):


import sys
import itertools

N = int(input())

P = list(map(int, sys.stdin.readline().strip().split()))
Q = list(map(int, sys.stdin.readline().strip().split()))


count = 1
a, b = 0, 0
for i in itertools.permutations([i for i in range(1, N+1)]):
    i = list(i)
    if i == P:
        a = count
    if i == Q:
        b = count
    count += 1

print(abs(a - b))

Solution (Python):
import itertools
n = int(input())
p= "".join(input().split())
q= "".join(input().split())

ans=[]
for s in itertools.permutations([str(i+1) for i in range(n)]):
    ans.append("".join(s))
sorted(ans)
print(abs(ans.index(p)-ans.index(q)))

Solution (Python):
from itertools import permutations
import numpy as np

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

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

    print(np.abs(a-b))

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

count = 1
for case in permutations([i+1 for i in range(N)]):
    if case == P:
        p_num = count
    
    if case == Q:
        q_num = count

    count += 1

print(abs(p_num-q_num))

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

flg = False
cnt = 0
for pi, qi in zip(p, q):
  if pi != qi:
    break
  cnt += 1
p[cnt:]
q[cnt:]
if cnt == n:
  print(0)
elif cnt == 0:
  bigger = p if p[cnt] > q[cnt] else q
  smaller = p if p[cnt] < q[cnt] else q

  perm = math.factorial(len(bigger[cnt+1:]))
  c = bigger[0] - smaller[0] - 1
  before = c * perm
  
  summation = 1
  for i in range(cnt+1, n):
    c = np.array(list(map(int, bigger[:i]<bigger[i]))).sum()
    perm = math.factorial(len(bigger[i+1:]))
    summation += (bigger[i]-c-1)*perm
    
  perm = math.factorial(len(smaller[cnt+1:]))
  
  summation2 = 1
  for i in range(cnt+1, n):
    c = np.array(list(map(int, smaller[:i]<smaller[i]))).sum()
    perm2 = math.factorial(len(smaller[i+1:]))
    summation2 += (smaller[i]-c-1)*perm2

  after = perm-summation2
  print(before + summation + after)  

else:
  bigger = p if p[cnt] > q[cnt] else q
  smaller = p if p[cnt] < q[cnt] else q
  u = bigger[cnt] - smaller[cnt] 
  c = np.array(list(map(int, bigger[:cnt]<u))).sum()
  
  perm = math.factorial(len(bigger[cnt+1:]))
  before = (bigger[cnt]-c) * perm
  
  summation = 0
  for i in range(cnt+1, n):
    c = np.array(list(map(int, bigger[:i]<bigger[i]))).sum()
    perm = math.factorial(len(bigger[i+1:]))
    summation += (bigger[i]-c-1)*perm
  
  perm = math.factorial(len(smaller[cnt+1:]))
  
  summation2 = 0
  for i in range(cnt+1, n):
    c = np.array(list(map(int, smaller[:i]<smaller[i]))).sum()
    perm = math.factorial(len(smaller[i+1:]))
    summation2 += (smaller[i]-c-1)*perm
  after = perm-summation2
  
  print(before + summation + after)

Solution (Python):
N = int(input())
P = list(map(int, input().split()))
Q=list(map(int, input().split()))
l = [i for i in range(N)]

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 permutations
n  = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
comb = list(permutations([i for i in range(1, n + 1)]))
comb.sort()
a = 0
b = 0

for i in range(len(comb)):
    if list(comb[i]) == P:
        a = i
    if list(comb[i]) == Q:
        b = i
ans = abs(a - b)
print(ans)

Solution (Python):
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
L = [i for i in range(1,N+1)]
R = [i for i in range(1,N+1)]

A,B = 0,0
for i in range(N-1):
 
  A += L.index(P[i])
  B += R.index(Q[i])
  A *= N-i-1
  B *= N-i-1
  L[L.index(P[i])] = 10
  R[R.index(Q[i])] = 10
  L.sort()
  R.sort()
  
print(abs(A-B))

Solution (Python):
import itertools

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

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

a, b = 0, 0
for i, v in enumerate(lst):
    if v == p:
        a = i + 1
    if v == q:
        b = i + 1

print(abs(a - b))

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

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

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)]
for i,per in enumerate(list(permutations(a))):
    if per == p:
        x = i
    if per == q:
        y = i
print(abs(x-y))

Solution (Python):
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
L = [i+1 for i in range(N)]
R = [i+1 for i in range(N)]
A,B = 0,0
for i in range(N-1):
    A *= N-i
    B *= N-i
    A += L.index(P[i])
    B += R.index(Q[i])
    L[L.index(P[i])] = 100
    R[R.index(Q[i])] = 100
    L.sort()
    R.sort()
print(abs(A-B))

Solution (Python):
from itertools import permutations


N = int(input())

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

all_p = list(permutations(range(1, N + 1, 1)))
print(abs((all_p.index(a) + 1) - (all_p.index(b) + 1)))

Solution (Python):
import itertools

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

seq_list = {}
i = 1
for seq in itertools.permutations(range(1, n+1), n):
    seq_list['_'.join(map(str, seq))] = i
    i += 1

a = seq_list['_'.join(map(str, p))]
b = seq_list['_'.join(map(str, q))]
print(abs(a-b))

Solution (Python):
import itertools
n=int(input())
plist=list(input().split())
qlist=list(input().split())
p=str("".join(plist))
q=str("".join(qlist))

numlist=[str(i+1) for i in range(n)]
jun=[]
for v in itertools.permutations(numlist,n):
	jun.append("".join(v))

print(abs(jun.index(p)-jun.index(q)))

Solution (Python):
import itertools

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

per_list = itertools.permutations([x+1 for x in range(n)])

p_dict_i = -1
q_dict_i = -1
for dict_i, per in enumerate(per_list):
    p_flg = True
    for i, num in enumerate(per):
        if num != p_list[i]:
            p_flg = False
            break
    q_flg = True
    for i, num in enumerate(per):
        if num != q_list[i]:
            q_flg = False
            break
    if p_flg: p_dict_i = dict_i
    if q_flg: q_dict_i = dict_i

print(abs(p_dict_i-q_dict_i))

Solution (Python):
import sys
def S(): return sys.stdin.readline().rstrip()
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())

import itertools
import math

n = I()
p = LI()
q = LI()
nums = range(1,n+1)

count = 0
for lis in itertools.permutations(nums,n):
    pflg = True
    qflg = True
    for i in range(n):
        if(p[i] != lis[i]):
            pflg = False
        if(q[i] != lis[i]):
            qflg = False
    if(pflg):
        a = count
    if(qflg):
        b = count
    count += 1

print(abs(b-a))

Solution (Python):
import itertools, math

n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
flag = True
if p == q:
    print(0)
else:
    for i, lst in enumerate(itertools.permutations(range(1, n + 1), n)):
        if lst == p or lst == q:
            if flag:
                ans = i
                flag = False
            else:
                print(i - ans)
                break

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

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()))
A = [v for v in itertools.permutations(l)]
a = 0
b = 0
A = sorted(A)
for i in range(len(A)):
  if A[i] == P:
    a = i+1
  if A[i] == Q:
    b = i+1
print(abs(a-b))

Solution (Python):
import itertools

N = int(input())
P, Q = [list(map(int, input().split())) for _ in range(2)]

for i, v in enumerate(itertools.permutations(range(1, N+1))):
    if list(v) == P:
        a = i
    if list(v) == Q:
        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
cmb=list(permutations(range(1,n+1),n))


a=0
b=0

for i in range(len(cmb)):
    if cmb[i]==p:
            a=i+1
    else:
            continue
    
    for j in range(len(cmb)):
        if cmb[j]==q:
            b=j+1
           
        else:
            continue


print(abs(a-b))

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





anum=0
bnum=0
x = [i for i in range(1,n+1)]
candi = itertools.permutations(x)
for i,data in enumerate(candi):
  if not anum:
    if list(data) == a:
      anum = i+1
  if not bnum:
    if list(data) == b:
      bnum = i+1
  if anum and bnum:
    break

print(abs(bnum-anum))

Solution (Python):
import itertools

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

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

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

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):
    a += (p[i] - 1) * math.factorial(N - i - 1)
    for j in range(i + 1, N):
        if p[j] > p[i]:
            p[j] -= 1

for i in range(N):
    b += (q[i] - 1) * math.factorial(N - i - 1)
    for j in range(i + 1, N):
        if q[j] > q[i]:
            q[j] -= 1

print(abs(a - b))

Solution (Python):
import itertools

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


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

cnt_perm = []
for perms in itertools.permutations(perm, n):
    cnt_perm.append(list(perms))

print(abs(cnt_perm.index(p)- cnt_perm.index(q)))

Solution (Python):
from sys import stdin, setrecursionlimit


def find(arr, n):
    arr_2 = sorted(arr)
    for i in range(len(arr_2)):
        if arr_2[i] == n:
            return i


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

    f = [1] * n
    for i in range(n - 1):
        f[i + 1] = f[i] * (i + 2)

    ans_p = 0
    ans_q = 0
    tmp_p = p
    tmp_q = q
    for i in range(n):
        p_i = find(tmp_p, tmp_p[0])
        tmp_p = tmp_p[1:]
        ans_p += p_i * f[len(tmp_p) - 1]
        q_i = find(tmp_q, tmp_q[0])
        tmp_q = tmp_q[1:]
        ans_q += q_i * f[len(tmp_q) - 1]
    print(abs(ans_q - ans_p))


if __name__ == "__main__":
    setrecursionlimit(10000)
    main()

Solution (Python):
import itertools

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

l = [i+1 for i in range(n)]
ll = []
p_= 0
q_= 0
for i in itertools.permutations(l,n):
    ll.append(i)

for i in ll:
    if list(i) == p:
        p_ = ll.index(i)+1
    if list(i) == q:
        q_ = ll.index(i)+1

print(abs(p_ - q_))

Solution (Python):
N=int(input())
P=list(map(int, input().split()))
Q=list(map(int, input().split()))
A=[]
for n in range(1,N+1):
    A.append(n)
import itertools
cnt=0
a=0;b=0
for i in list(itertools.permutations(A)):
    cnt+=1
    i=list(i)
    if P==i:
        a=cnt
    if Q==i:
        b=cnt
    if (a!=0) and (b!=0):
        print(abs(a-b))
        break

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    import numpy as np

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

    import itertools
    X = [i+1 for i in range(N)]
    for i, v in enumerate(itertools.permutations(X)):
        v = np.array(v)
        if (v == P).all():
            p = i
        if (v == Q).all():
            q = i
    print(abs(p-q))


if __name__ == "__main__":
    main()

Solution (Python):
import itertools

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

l = list(itertools.permutations([i+1 for i in range(n)], n))
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()))
c = 1
pn = 0
qn = 0
lst = [i for i in range(1, N+1)]
for i in itertools.permutations(lst, N):
    if i == P:
        pn = c
    if i == Q:
        qn = c
    c += 1
print(abs(pn - qn))

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

for n, i in enumerate(permutations(sorted(p))):
    if i == p:
        pn = n

for n, i in enumerate(permutations(sorted(q))):
    if i == q:
        qn = n
print(abs(pn-qn))

Solution (Python):
from itertools import permutations
from math import factorial

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

A = []
for perm in permutations(range(1, N+1), N):
    A.append(int("".join([str(n) for n in perm])))
a = A.index(P)
b = A.index(Q)
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, combinations,combinations_with_replacement,product

a = range(1,N+1)
PP = list(permutations(a))


if P==Q:
    print(0)

else:
    flag=0
    i=0
    while True:
        if P == PP[i]:
            a = i+1
            flag+=1
            
            if flag==2:
                break
        elif Q == PP[i]:
            b = i+1
            flag+=1
            
            if flag==2:
                break
        i+=1

    print(abs(a-b))

Solution (Python):
from itertools import permutations as p

N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
a=0
b=0
for i,value in enumerate(sorted(list(p(P,N)))):
    if list(value)==P:
        a=i
    if list(value)==Q:
        b=i
print(abs(a-b))

Solution (Python):
import itertools


N = int(input())

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

p_index = -1
q_index = -1
permutation_list = list(itertools.permutations([x + 1 for x in range(N)]))
for i in range(len(permutation_list)):
    param = "".join(map(str, permutation_list[i]))
    if P == param:
        p_index = i
    if Q == param:
        q_index = i
    if p_index != -1 and q_index != -1:
        print(abs(p_index - q_index))
        exit(0)

Solution (Python):
import itertools


N = int(input())

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



p_index = -1
q_index = -1
permutation_list = list(itertools.permutations([x + 1 for x in range(N)]))

for i in range(len(permutation_list)):
    
    param = "".join(map(str, permutation_list[i]))
    if P == param:
        p_index = i
    if Q == param:
        q_index = i
    if p_index != -1 and q_index != -1:
        result = p_index - q_index
        if result < 0:
            result = -result
        print(result)
        exit(0)

Solution (Python):
def resolve():
    import itertools
    n = int(input())
    p = tuple([int(i) for i in input().split()])
    q = tuple([int(i) for i in input().split()])

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

    print(abs(all_list.index(p) - all_list.index(q)))


resolve()

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

Solution (Python):

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

def lexCal(p):
	ans = 0
	used = set()
	for i in range(N):
		x = p[i]
		for y in range(1,x):
			if not y in used:
				ans += math.factorial(N-1-i)
		used.add(x)
	return ans

print(abs(lexCal(p)-lexCal(q)))

Solution (Python):
import itertools

N = int(input())
P = input()
Q = input()
pn =0
qn =0
count =0
for x in itertools.permutations(range(1,N+1,1)):
    count+=1
    tmp = " ".join(list(map(str,x)))
    if tmp == P:
        pn = count
    if tmp == Q:
        qn = count
print(abs(qn-pn))

Solution (Python):

import sys
import math
from collections import defaultdict
import itertools
read = sys.stdin.buffer.read
readline = sys.stdin.readline
readlines = sys.stdin.buffer.readlines

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

hp = defaultdict(int)
per = list(itertools.permutations((i for i in range(1,N+1)) , N))
for index , p in enumerate(per) :
    hp[p] = index
print(abs(hp[Q] - hp[P]))

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

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

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

print(abs(p-q))

Solution (Python):
import copy

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

a_list = []

def dfs(n, m, l):
    
    
    
    if l.count(0) == 0:
        a_list.append(l)
        return
    else:
        for i in range(n):
            if l[i] == 0:
                a = copy.copy(l)
                a[i] = m
                dfs(n, m+1, a)

dfs(n, 1, [0 for _ in range(n)])
a_list.sort()
print(abs(a_list.index(p)-a_list.index(q)))

Solution (Python):
import itertools

N = int(input())
N_list = [i for i in range(1, N+1)]

A = tuple(map(int, input().split()))
B = tuple(map(int, input().split()))

N_pattern = list(itertools.permutations(N_list))

print(abs(N_pattern.index(A) - N_pattern.index(B)))

Solution (Python):
import itertools, sys

N = int(input())
N_list = [i for i in range(1, N+1)]

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

if A == B:
    print('0')
    sys.exit()
for v, i  in enumerate(list(itertools.permutations(N_list))):
    i = list(i)
    if A == i:
        a = v
    elif B == i:
        b = v

print(abs(a-b))

Solution (Python):
import math

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

def calc(ary):
    remain = sorted(ary)

    fact = {}
    for r in remain:
        fact[r] = math.factorial(r)
    fact[0] = 1

    result = 0
    max_length = len(ary)
    for i in range(len(ary)):
        ai = ary[i]
        cnt = 0
        for j in range(len(remain)):
            rj = remain[j]
            if ai == rj:
                result += j * fact[max_length - i-1]
                remain.remove(rj)
                break
            cnt += 1
    return result

print(int(math.fabs(calc(P) - calc(Q))))

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

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

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

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

import itertools

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

C = list(itertools.permutations(a))

idxs = []

for i, c in enumerate(C):
    l = list(c)
    if l == p:
        idxs.append(i)
    if l == q:
        idxs.append(i)

ans = idxs[1]-idxs[0]

print(ans)

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()))
l=list(itertools.permutations(range(1,n+1)))
print(abs(l.index(p)-(l.index(q))))

Solution (Python):
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
Iq=list(i for i in range(1,N+1))
Ip=list(i for i in range(1,N+1))

import math

q = 0
p = 0

for i in range(N):
    q += Iq.index(Q[i])*math.factorial(N-i-1)
    p += Ip.index(P[i])*math.factorial(N-i-1)
    Iq.remove(Q[i])
    Ip.remove(P[i])

print(max(p-q,q-p))

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


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

cnt = 0
for i ,j in enumerate(n_list):
    
    j = list(j)
    if j == p:
        x = i + 1
    if j == q:
        y = i + 1
print(abs(x-y))

Solution (Python):
import math

n1 = int(input())
n2 = [int(i) for i in input().split()]
n3 = [int(i) for i in input().split()]

a1 = []
a2 = []
for i1 in range(n1):
    a1.append(i1 + 1)
    a2.append(i1 + 1)

c4 = 0
for i5 in range(n1 - 1):
    c4 += (a1.index(n2[i5])) * math.factorial(n1 - i5 - 1)
    a1[a1.index(n2[i5])] = n1
    a1.sort()

c5 = 0
for i6 in range(n1- 1):
    c5 += (a2.index(n3[i6]) ) * math.factorial(n1 - i6 - 1)
    a2[a2.index(n3[i6])] = n1
    a2.sort()

print(abs(c5 - c4))

Solution (Python):
import itertools

n,count=int(input()),0
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ans=[]

for i in itertools.permutations(range(1,n+1)):
  li = list(i)
  count += 1
  if li == a:
    ans.append(count)
  if li == b:
    ans.append(count)

print(abs(ans[1]-ans[0]))

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

"""
Created on Sat May  9 14:24:12 2020

@author: shinba
"""

import itertools

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
for i in itertools.permutations(a):
    cnt += 1
    if i == p:
        a = cnt
    if i == q:
        b = cnt

print(abs(a-b))

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