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 permute(s, low, high, arr):
    if low == high:
        arr.append(''.join(s))
    for i in range(low, high+1):
        s[i], s[low] = s[low], s[i]
        permute(s, low+1, high, arr)
        s[low], s[i] = s[i], s[low]



n = int(input())
A = input()
B = input()
A = A.replace(' ', '')
B = B.replace(' ', '')
arr = []
permute(list(A), 0, n-1, arr)
arr.sort()
print(abs(arr.index(A)-arr.index(B)))

Solution (Python):
import itertools

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

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

pindex=A.index(P)+1
qindex=A.index(Q)+1

print(abs(pindex-qindex))

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

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

def factorial(x):
	ans = 1
	for i in range(2, x+1):
		ans *= i
	return ans
	
def order(P):
	ranks = []
	used = [False] * (n+1)
	for i in range(n):
		c = P[i]
		j = 1
		rank = 0
		while j <= c:
			if not used[j]:
				rank += 1
			j += 1
		used[c] = True
		ranks.append(rank)
	return rank2order(ranks)
	
def rank2order(ranks):
	ng = factorial(n)
	order = 1
	for i in range(n-1):
		ng = ng // (n-i)
		order += ng*(ranks[i]-1)
	return order


a = order(P)
b = order(Q)
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()])

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

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

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

Solution (Python):
from itertools import permutations

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

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

print(abs(a-b))

Solution (Python):
from itertools import permutations

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

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

Solution (Python):
import math

def order(A):
  l=len(A)
  acu=[0 for _ in range(l+1)]
  res=1
  num=l-1
  for a in A:
    res+=(a-1-acu[a])*math.factorial(num)
    num-=1
    for i in range(a, l+1):
      acu[i]+=1
  return res

N=int(input())
P=list(map(int, input().split()))
Q=list(map(int, input().split()))
print(abs(order(P)-order(Q)))

Solution (Python):
def kaijyo(num):
  ans = 1
  for i in range(num):
    ans = ans * (i + 1)
  return ans

N = int(input())
P = list(map(int,input().rstrip().split(" ")))
Q = list(map(int,input().rstrip().split(" ")))
ap = [(i + 1) for i in range(N)]
aq = [(i + 1) for i in range(N)]
Pa = 0
Qa = 0
for i in range(N):
  Pa += ap.index(P[i]) * kaijyo(N - i - 1)
  ap.pop(ap.index(P[i]))
for i in range(N):
  Qa += aq.index(Q[i]) * kaijyo(N - i - 1)
  aq.pop(aq.index(Q[i]))
print(abs(Pa - Qa))

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

Solution (Python):
import sys
import itertools as it
input = sys.stdin.readline


def main():
    N = int(input())
    p = tuple(int(c) for c in input().split())
    q = tuple(int(c) for c in input().split())

    a = -1
    b = -1
    for i, t in enumerate(it.permutations(range(1,N+1)),1):
        if a != -1 and b != -1:
            break
        if t == p: a = i
        if t == q: b = i

    print(abs(a - b))

if __name__ == "__main__":
    main()

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 = 0
b = 0
for n, val in enumerate(l):
    if list(val) == P:
        a = n+1
    if list(val) == Q:
        b = n+1
        if a != 0:
            break
print(abs(a-b))

Solution (Python):
import itertools


from collections import defaultdict

con = 10 ** 9 + 7

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


def main():
	N = int(input())
	P = tuple(map(int, input().split()))
	Q = tuple(map(int, input().split()))
	a = None
	b = None
	seq = [i for i in range(1, N + 1)]
	L = list(itertools.permutations(seq))
	M = len(L)
	for i in range(M):
		if P == L[i]:
			a = i
		if Q == L[i]:
			b = i

	print(abs(a - b))

if __name__ == '__main__':
	main()

Solution (Python):
n = int(input())
p = [int(s) for s in input().split()]
q = [int(s) for s in input().split()]
pp = []
qq = []
for i in range(n):
    pp.append(0)
    qq.append(0)
for i in range(n-1):
    for j in range(n-i-1):
        if(p[i]>p[j+i+1]):
            pp[i]=pp[i]+1
        if(q[i]>q[j+i+1]):
            qq[i]=qq[i]+1
a = 0
b = 0
x = 1
for i in range(n-1):
    a = a + pp[n-i-2]*x
    b = b + qq[n-i-2]*x
    x = x*(i+2)
if (a>=b):
    print(int(a-b))
else:
    print(int(b-a))

Solution (Python):
from itertools import permutations

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

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

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

from itertools import permutations
a, b = None, None
for num, tmp in enumerate(permutations(range(N), r=N)):
    dictord = []
    for i in tmp:
        dictord.append(i + 1)

    if dictord == P:
        a = num
    if dictord == Q:
        b = num
    if a is not None and b is not None:
        break

print(abs(a-b))

Solution (Python):
n = int(input())
p = [ int(i) for i in input().split(" ")]
q = [ int(i) for i in input().split(" ")]

def permutation(list):
  if len(list) == 0:
    return []
  
  if len(list) == 1:
    return [list]

  result = []

  for i in range(len(list)):
    base = list[i]
    can = list[:i] + list[i+1:]
    for p in permutation(can):
      result.append([base] + p) 
  
  return result

result = sorted(permutation([i for i in range(1, n+1)]))
print( abs(result.index(q) - result.index(p)))

Solution (Python):
def permutationIndex(A):
  if A is None or len(A) ==0:
    return 0
  index = 1
  factor = 1
  for i in range(len(A)-1,-1,-1):
    rank = 0
    for j in range(i+1,len(A)):
      if A[i] > A[j]:
        rank+=1
    index += rank*factor
    factor *= (len(A)-i)
  return index
n = int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
print(abs(permutationIndex(p)-permutationIndex(q)))

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

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

l = []
def permutation(start, end):
    if end==start:
        
        t = a[::]
        l.append(tuple(t))
        return
    for i in range(start, end+1):
        a[i],a[start] = a[start],a[i]
        permutation(start+1, end)
        a[i],a[start] = a[start],a[i]
permutation(0,len(a)-1)
l.sort()
x,y=0,0
for i in range(len(l)):
    if l[i]==tuple(a):
        x = i
    if l[i] == tuple(b):
        y=i

print(abs(x-y))

Solution (Python):
from itertools import permutations

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

cnt = 0

for i in permutations([i for i in range(1, N+1)]):
    a_cnt = 0
    b_cnt = 0
    for j in range(N):
        if i[j] == P[j]:
            a_cnt += 1

        if i[j] == Q[j]:
            b_cnt += 1

    if a_cnt == N:
        a = cnt

    if b_cnt == N:
        b = cnt

    cnt += 1

print(abs(a-b))

Solution (Python):
import itertools
n = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
L = list(itertools.permutations([i for i in range(1,n+1)]))
print(
    abs((L.index(P)+1)-((L.index(Q)+1)))
    )

Solution (Python):
import itertools

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

l=[]
k=1

for i in range(N):
    l.append(k)
    k=k+1


m=[]    
for v in itertools.permutations(l, N):
    m.append(v)
m.sort()
a=m.index(P)
b=m.index(Q)

print(abs(a-b))

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

fact = [1] * (N+1)
for i in range(2,N+1):
    fact[i] = fact[i-1]*i


def dic_num(S):
    keta = 0
    num = 0
    S_set = set()
    for i in range(len(S)):
        minor = 0
        for j in S_set:
            if S[keta] > j:
                minor = minor + 1
        num += (S[keta] - 1 - minor) * fact[len(S)-keta-1]
        S_set.add(S[keta])
        keta += 1

    return num+1


print(abs(dic_num(P)-dic_num(Q)))

Solution (Python):
import math
import itertools

N = int(input())
Nlist = [0 for i in range(N)]
for i in range(N):
    Nlist[i] = i+1

Plist =list(itertools.permutations(Nlist))

Pn = input().split()
Pn = [int(i) for i in Pn]
Qn = input().split()
Qn = [int(i) for i in Qn]

def Order(A, Plist):
    
    num = -1
    for i in range(len(Plist)):
        if(list(A) == list(Plist[i])):
            num = i+1
            break
    return num

print(int(math.fabs(Order(Pn, Plist)-Order(Qn, Plist))))

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

def cur(n,N,x,List,kouho):
    if n ==0:
        List.append(x)
        return 0
    for i in kouho:
        
        x_new = x + [i]
        Index = kouho.index(i)
        new_kouho = kouho[0:Index]+kouho[Index+1:len(kouho)]
       
        cur(n-1,N,x_new,List,new_kouho)

x = []
cur(N,N,x,List,digit)

num_p = List.index(P)
num_q = List.index(Q)

print(abs(num_p-num_q))

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



def kai(s):
    var = s
    for i in range(1, s):
        var = var * i
    return var

def jun (v):
    l = [i for i in range(1, n + 1)]
    vn = 1
    for i in range(len(v)):
        tmp  = int(v[i])
        tmp_l = list(filter(lambda x: x < tmp, l))
        vn += len(tmp_l) * kai(len(l)-1)
        l.remove(tmp)
    return vn

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

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

Solution (Python):

import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline






















def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

def main():
	N = inputInt()
	P = inputList()
	Q = inputList()

	PP = tuple(P)
	QQ = tuple(Q)

	nums = []
	for j in range(1,N+1):
		nums.append(j)

	p = itertools.permutations(nums, N)
	cont = 0
	tmpP = 0
	tmpQ = 0
	for v in p:
		cont += 1
		if v == PP:
			tmpP = cont
		if v == QQ:
			tmpQ = cont

	print(abs(tmpP-tmpQ))


if __name__ == "__main__":
	main()

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

import itertools

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

ans = []
for v in itertools.permutations(l):
    ans.append(" ".join(v))

a = ans.index(p)
b = ans.index(q)
print(abs(a-b))

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

import itertools

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

b = list(itertools.permutations(a))

b = list(map(list, b))

for i in range(len(b)):
    if b[i] == p:
        buf1 = i

    if b[i] == q:
        buf2 = i


print(abs(buf1 - buf2))

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

Solution (Python):


import itertools
n = int(input())
a = ''.join(input().split(' '))  
b = ''.join(input().split(' '))  

p = 0
q = 0
i = 0
for it in itertools.permutations(range(1, n + 1)):
    it = list(it)  
    it = ''.join([str(num) for num in it])  
    if it == a:  
        p = i
    if it == b:  
        q = i

    i += 1
print(abs(p-q))

Solution (Python):
def cre_permu(a, temp, unused, digit):
    if digit==n:
        a.append(temp*10+unused[0])
        
        return
    else:
        for i in unused:
            cre_permu(a, temp*10+i, [k for k in unused if k!=i], digit+1)
    return

n = int(input())
p = int(input()[0::2])
q = int(input()[0::2])
lis = []
cre_permu(lis, 0, [i for i in range(1, n+1)], 1)
print(abs(lis.index(p)-lis.index(q)))

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

p = ''
q = ''
for i in range(N):
    p += str(P[i])
    q += str(Q[i])
    
import itertools
A = [i for i in range(1,N+1)]
L = []

for i in itertools.permutations(A,N):
    tmp = ''
    for j in i:
        tmp += str(j)
    L.append(tmp)
L.sort()

for i in range(len(L)):
    if L[i]==p:
        PP = i
    if L[i]==q:
        QQ = i
print(abs(PP-QQ))

Solution (Python):
import sys
import math
input = sys.stdin.readline

N = int(input())
pp = list(map(int, input().split()))
qq = list(map(int, input().split()))

a = 1
b = 1
a_left = [i+1 for i in range(N)]
b_left = [i+1 for i in range(N)]
for i in range(N-1):
	num = math.factorial(N-i-1)
	a += (num)*(a_left.index(pp[i]))
	a_left.remove(pp[i])
	b += (num)*(b_left.index(qq[i]))
	b_left.remove(qq[i])

print(abs(a-b))

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

Solution (Python):
import itertools
N=int(input())
A=int(input().replace(' ',''))
B=int(input().replace(' ',''))
seed = [str(i+1) for i in range(N)]
L = {int(''.join(x)):i for i,x in enumerate(itertools.permutations(seed, N))}
print(abs(L[A]-L[B]))

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

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

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

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

Solution (Python):
import math

N=int(input())
NP=list(range(N+1)[1:])
NQ=list(range(N+1)[1:])
P=list(map(int,input().split()))
Q=list(map(int,input().split()))

a=0
b=0

for n in range(N):
    a+=(math.factorial(N-n-1))*NP.index(P[n])
    b+=(math.factorial(N-n-1))*NQ.index(Q[n])
    NP.pop(NP.index(P[n]))
    NQ.pop(NQ.index(Q[n]))

print(abs(a-b))

Solution (Python):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
L = [[] for i in range(9)]
L[2] = [[1, 2], [2, 1]]
for i in range(3, 9):
  for j in range(i):
    for l in L[i-1]:
      k = list(l)
      k.insert(j, i)
      L[i].append(k)
  L[i].sort()

p = L[N].index(P)
q = L[N].index(Q)
print(abs(p-q))

Solution (Python):


import itertools

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

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

for i, p in enumerate(perm):

    if p == P:
        a = i + 1
    if p == Q:
        b = i + 1

print(abs(a - b))

Solution (Python):
import itertools
import math

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

P_index = ''.join(map(str, P))
Q_index = ''.join(map(str, Q))
S = ''.join(map(str, sorted(P)))

Index = [''.join(i) for i in itertools.permutations(S)]
 
print(abs(Index.index(P_index)-Index.index(Q_index)))

Solution (Python):
from itertools import permutations

N = int(input())
P = tuple([int(zz)-1 for zz in input().split()])
Q = tuple([int(zz)-1 for zz in input().split()])

li = list(permutations(range(N)))
print(abs(li.index(P)-li.index(Q)))

Solution (Python):
memo=[1]*10
def fac(N):
    if N==0:return 1
    elif memo[N]==1:
        memo[N]=N*fac(N-1)
    return memo[N]

def dic(S,N):
    res=0
    nums=list(range(N+1))
    for i in range(N-1):
        res+=(nums.index(S[i])-1)*fac(N-i-1)
        nums.pop(nums.index(S[i]))
    return res+1

N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
print(abs(dic(P,N)-dic(Q,N)))

Solution (Python):
N=int(input())
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
from itertools import permutations
L=list(permutations(list(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()))

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

Solution (Python):
from itertools import permutations

n = int(input())
nums1 = list(map(int,input().split(" ")))
nums2 = list(map(int,input().split(" ")))

t1 = tuple(nums1)
t2 = tuple(nums2)

index = 1
a = b = -1

for perm in permutations(list(range(1,n+1))):
    if perm == t1:
        a = index
    if perm == t2:
        b = index
    index += 1

print(abs(a-b))

Solution (Python):
from itertools import permutations

n = int(input())
nums1 = list(map(int,input().split(" ")))
nums2 = list(map(int,input().split(" ")))

t1 = tuple(nums1)
t2 = tuple(nums2)

index = 1
a = b = -1

for perm in permutations(list(range(1,n+1))):
    if perm == t1:
        a = index
    if perm == t2:
        b = index
    index += 1

print(abs(a-b))

Solution (Python):
from itertools import permutations
n = int(input())
p_nums = tuple([int(i) for i in input().split()])
q_nums = tuple([int(i) for i in input().split()])

tmp = permutations(range(1, n+1))
d = {tuple(permu): i for i, permu in enumerate(tmp, 1)}

print(abs(d[p_nums] - d[q_nums]))

Solution (Python):
import itertools

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

Solution (Python):
import itertools

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

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

Solution (Python):
import itertools
import math
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
A= (sorted(P))
P1 = ''.join(map(str,P))
Q1 = ''.join(map(str,Q))
B = ''.join(map(str,A))
anagram_list = [''.join(v) for v in itertools.permutations(B)]

print(abs(anagram_list.index(P1)-anagram_list.index(Q1)))

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

print(ans)

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()])
per = list(itertools.permutations(range(1, N+1)))

print(abs((per.index(P)+1) - (per.index(Q)+1)))

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a_value_list = []
a_real_list = [1]
a_real = []
b_value_list = []
b_real_list = [1]
b_real = []
a_ans = 1
b_ans = 1
c = []


for i in range(n):
    a_value_list.append(1)
    b_value_list.append(1)

""""
x = a[0]-1
value_list[x] = 0
print(value_list)
"""

for i in range(n):
    x = i + 1
    a_real_list.append(a_real_list[i]*x)
    a_real.append(x)
    b_real_list.append(b_real_list[i] * x)
    b_real.append(x)

a_real_list.pop(0)
b_real_list.pop(0)

for i in range(n-1):
    m = n-i-1
    x = a[i] - 1
    a_value_list[x] = 0
    c = a_value_list[:x+1]
    y = sum(c)
    a_ans += a_real_list[m]*y/a_real[m]


for i in range(n-1):
    m = n-i-1
    x = b[i] - 1
    b_value_list[x] = 0
    c = b_value_list[:x+1]
    y = sum(c)
    b_ans += b_real_list[m]*y/b_real[m]

print(int(abs(a_ans-b_ans)))

Solution (Python):
from itertools import permutations

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

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

count = 0
for i in permutations(lst):
    
    if i == P:
        a = count
    if i == Q:
        b = count
    count += 1

print (abs(a - b))

Solution (Python):

import sys
sys.setrecursionlimit(10000000)
INF = 1<<32


def solve(N: int, P: "List[int]", Q: "List[int]"):
    
    from itertools import combinations, permutations
    ans = [''.join(list(map(str, list(v)))) for v in permutations(P, N)]
    ans.sort()
    a = ans.index(''.join(list(map(str, P))))
    b = ans.index(''.join(list(map(str, Q))))
    print(abs(a-b))
    
    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    P = [int(next(tokens)) for _ in range(N)]  
    Q = [int(next(tokens)) for _ in range(N)]  
    solve(N, P, Q)

if __name__ == '__main__':
    main()

Solution (Python):
import itertools

n = int(input())
p = tuple(list(map(int,input().split())))
q = tuple(list(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(int(x) for x in input().split())
q=tuple(int(x) for x in input().split())
all=list(itertools.permutations(range(1,n+1)))
for idx,item in enumerate(all):
  if item==p:
    cp=idx
  if item==q:
    cq=idx
print(abs(cp-cq))

Solution (Python):

max = int(input())
a = ''.join(input().split())
b = ''.join(input().split())
petternArr = []

def makeArray(n,s):

  if n >= max:
    petternArr.append(s)
    return
  
  for i in range(max):
    if s.find(str(i+1)) == -1:
      tmp = s + str(i+1)
      makeArray(n+1,tmp)

makeArray(0,'')

petternArr.sort()

idxA = petternArr.index(a)
idxB = petternArr.index(b)

print(abs(idxA-idxB))

Solution (Python):
import itertools

n=int(input())
p=input().split()
q=input().split()

z=list(range(1,n+1))
z_str=[str(m) for m in z]
i=1

for v in list(itertools.permutations(z_str)):
  li=list(v)
  if p==li:
    a=int(i)
  if q==li:
    b=int(i)
  i=i+1

print(abs(a-b))

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

Solution (Python):

from itertools import permutations


def main():
    N = int(input())
    P = tuple(map(int, input().split()))
    Q = tuple(map(int, input().split()))
    perms = list(permutations(range(1, N + 1)))
    ans = abs(perms.index(P) - perms.index(Q))
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):

from itertools import permutations


def main():
    N, *PQ = map(int, open(0).read().split())
    P, Q = PQ[:N], PQ[N:]
    a, b = 0, 0
    for i, perm in enumerate(permutations(range(1, N + 1), N), 1):
        perm = list(perm)
        if perm == P:
            a = i
        if perm == Q:
            b = i
    ans = abs(a - b)
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
from itertools import permutations

N = int(input())
P = list(map(int, input().split()))
S = list(map(int, input().split()))
J = list(permutations(sorted(S) , N))

print(abs(J.index(tuple(P)) - J.index(tuple(S))))

Solution (Python):
import itertools
import math

n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
val = list(itertools.permutations(range(1,n+1)))

cntp = 0
cntq = 0
for i in range(len(val)):
    if p == val[i]:
        cntp = i+1
    if q == val[i]:
        cntq = i+1
print(int(math.fabs(cntp - cntq)))

Solution (Python):

import itertools


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

Z = []

for count in range(1,int(N)+1):
    Z.append(count)

zyun = itertools.permutations(Z)

abscount = 1
Pcount = 0
Qcount = 0

for cc in zyun:
    if list(cc) == P:
        Pcount = abscount
    if list(cc) == Q:
        Qcount = abscount
    abscount += 1

print(abs(Pcount - Qcount))

Solution (Python):
from itertools import permutations

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

p = 0
q = 0
for i, perm in enumerate(permutations([i for i in range(1, 1 + N)])):
    if perm == P:
        p = i
    if perm == Q:
        q = i
print(abs(p - q))

Solution (Python):
from itertools import permutations

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

xs = sorted([int(''.join(map(str, x))) for x in permutations(range(1, n+1))])

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

Solution (Python):
import math
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
s=0
t=0
for i in range(len(a)):
    k=0
    p=0
    for j in range(i+1,n):
        if a[i]>a[j]:
            k+=1
        if b[i]>b[j]:
            p+=1
    m=math.factorial(n-i-1)
    s+=m*k
    t+=m*p
 

print(abs(s-t))

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

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

Solution (Python):
def get_order(numbers, originals):
    
    from math import factorial
    from copy import copy
    numbers = copy(numbers)
    originals = copy(originals)
    
    total = 0
    while numbers:
        number = numbers.pop(0)
        number_index = originals.index(number)
        originals.pop(number_index)
        count = (number_index ) * factorial(len(originals))
        total += count
    return total
        
def get_next_int():
    return int(float(input()))
def get_next_ints(delim=" "):
    return tuple([int(float(x)) for x in input().split(delim)])

def main(print=__builtins__.print):
    n = get_next_int()
    
    a = list(get_next_ints())
    b = list(get_next_ints())
    originals = list(map(int, range(1, n+1)))
    print(abs(get_order(a, originals) - get_order(b, originals)))

if __name__ == '__main__':
    main()

Solution (Python):
from itertools import permutations as permu

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

l = [list(s) for s in permu(range(1, N+1))]
l.sort()

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

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

x=a.index(p)
y=a.index(q)
print(abs(x-y))

Solution (Python):
from itertools import permutations


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

for i, p in enumerate(permutations(range(1, N+1))):
    if list(p) == P:
        p_num = i
    if list(p) == Q:
        q_num = i
print(abs(p_num-q_num))

Solution (Python):
import itertools

N=int(input())
P=tuple(input().split())
Q=tuple(input().split())
R=sorted(list(itertools.permutations(P)))

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

Solution (Python):
import itertools

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

perms = [''.join(per) for per in itertools.permutations([str(n) for n in range(1, N + 1)], N)]
perms = sorted(perms)

l = perms.index(P)
r = perms.index(Q)
ma = max(l, r)
mi = min(l, r)
print(ma - mi)

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

import math

lst = [_ for _  in range(1,n+1)]

i = 1
lst = [_ for _  in range(1,n+1)]
for _ in p:
    idx = lst.index(_)
    i += math.factorial(len(lst)) // len(lst) * idx
    lst.remove(_)

pans = i

i = 1
lst = [_ for _  in range(1,n+1)]
for _ in q:
    idx = lst.index(_)
    i += math.factorial(len(lst)) // len(lst) * idx
    lst.remove(_)

qans = i

ans = abs(pans - qans)
print(ans)

Solution (Python):
import itertools

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

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

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

Solution (Python):
from itertools import permutations

N = int(input())
R = list(permutations(range(1,N+1)))
P = tuple(map(int, input().split(" ")))
Q = tuple(map(int, input().split(" ")))
print(abs(R.index(P)-R.index(Q)))

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

Solution (Python):
import itertools

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

Solution (Python):
a = int(input())
b = [int(i) for i in input().split(" ")]
c = [int(i) for i in input().split(" ")]


def cal(data):
    length = len(data)
    mem = [1] * length
    buf = [1]
    result = 0
    for i in range(1, length):
        buf.append(buf[i-1]*i)
    buf.reverse()
    for i in range(length):
        result += buf[i] * (sum(mem[:data[i]]))
        mem[data[i]-1] = 0
    return result


print(abs(cal(b)-cal(c)))