Problem:
 Score : 300 points    Problem Statement We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N) ).  There are N! possible permutations of size N . Among them, let P and Q be the a -th and b -th lexicographically smallest permutations, respectively. Find |a - b| .      Notes For two sequences X and Y , X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k .      Constraints  2 \leq N \leq 8  P and Q are permutations of size N .         Input Input is given from Standard Input in the following format:  N  P_1  P_2  ...  P_N  Q_1  Q_2  ...  Q_N       Output Print |a - b| .        Sample Input 1 3
1 3 2
3 1 2      Sample Output 1 3  There are 6 permutations of size 3 : (1,~2,~3) , (1,~3,~2) , (2,~1,~3) , (2,~3,~1) , (3,~1,~2) , and (3,~2,~1) . Among them, (1,~3,~2) and (3,~1,~2) come 2 -nd and 5 -th in lexicographical order, so the answer is |2 - 5| = 3 .       Sample Input 2 8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1      Sample Output 2 17517       Sample Input 3 3
1 2 3
1 2 3      Sample Output 3 0

Solution (Python):
from math import factorial


def solve(n,lst):
    nums = list(range(1,n+1))
    counter = 0
    for i in range(n):
        counter += (nums.index(lst[i])) * factorial(n-i-1)
        nums.pop(nums.index(lst[i]))
    return counter + 1




def main():
    n = int(input())
    lst1 = list(map(int,input().split()))
    lst2 = list(map(int,input().split()))
    lst1_ans = solve(n,lst1)
    lst2_ans = solve(n,lst2)
    answer = abs(lst1_ans - lst2_ans)
    print(answer)
if __name__ == '__main__':
    main()

Solution (Python):
from math import factorial
from itertools import permutations
n=int(input())
a=[]
ansp="a"
ansq="a"
p=[int(x) for x in input().split()]
q=[int(x) for x in input().split()]
for v in permutations(p, n):
    a.append(list(v))
a.sort()
for i in range(len(a)):
    if a[i]==p:
        ansp=i
    if a[i]==q:
        ansq=i
    if ansq!="a" and ansp!="a":
        break
print(max(ansp,ansq)-min(ansp,ansq))

Solution (Python):
import itertools
n = int(input())
l = [i for i in range(1, n+1)]
l = list(itertools.permutations(l))

p = input()
q = input()
p = p.split(" ")
q = q.split(" ")
p, q = tuple(map(int, p)), tuple(map(int, q))
print(abs(l.index(p) - l.index(q)))

Solution (Python):

import sys
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something : print(*something) if DEBUG else 0
DEBUG = False
def main(given = sys.stdin.readline):
    input = lambda : given().rstrip()
    LMIIS = lambda : list(map(int,input().split()))
    II = lambda : int(input())
    XLMIIS = lambda x : [LMIIS() for _ in range(x)]

    N = II()
    P = input().replace(' ','')
    Q = input().replace(' ','')

    kouho = set(range(1,N+1))
    def kaijo(n):
        ans = 1
        for i in range(1,n+1):
            ans *= i
        return ans
    numbers = [0] * kaijo(N)
    
    from copy import copy
    def mkp(kouho,i,p):
        if i == N-1:
            numbers.append(p+kouho[0])
            return

        for j in range(len(kouho)):
            kouho2 = copy(kouho)
            kouho2.remove(kouho[j])
            mkp(kouho2,i+1,p+kouho[j])
    mkp(list(map(str,range(1,N+1))),0,'')
    numbers = numbers[kaijo(N):]


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



   




if __name__ == '__main__':
    main()

Solution (Python):
import math
N=int(input())
lst=[int(s) for s in input().split()]
lst2=[int(s) for s in input().split()]
def ind(ls):
  cha=[i+1 for i in range(N)]
  ans=1
  for i in range(N):
    x=cha.index(ls[i])
  
    ans+=(x)*math.factorial(N-1-i)
   
    cha.remove(ls[i])
  return ans
a=ind(lst)
b=ind(lst2)
print(abs(a-b))

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

l = (i+1 for i in range(n))
import itertools
L =[]
for perm in itertools.permutations(l,n):
    L.append(perm)
import bisect

pi = bisect.bisect_left(L,p)
qi = bisect.bisect_left(L,q)

print(abs(qi-pi))

Solution (Python):

import sys

def kaijyo(n):
    if n == 0:
        return 1
    return n * kaijyo(n-1)

def z(n):
    return -n if n<0 else n

def numi(X, y):
    T = sorted(X)
    i = T.index(y)
    
    return i

def solve(N: int, P: "List[int]", Q: "List[int]"):
    ans=0
    for i in range(N):
        ans+=(numi(P[i:], P[i]) - numi(Q[i:], Q[i])) * kaijyo(N - i - 1)
        
    print(z(ans))
    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):
from itertools import permutations
N = int(input())
P = tuple(map(int,input().split(' ')))
Q = tuple(map(int,input().split(' ')))

perm = permutations([x for x in range(1,N+1)]) 
perm = list(perm)

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

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

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

permu = list(itertools.permutations(sec))

for i,v in enumerate(permu):
    
    if a == list(v):
        a_i = i+1
    if b == list(v):
        b_i = i+1

print(abs(a_i-b_i))

Solution (Python):
from itertools import permutations 

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

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

Solution (Python):
import itertools
n = int(input())
s = list(itertools.permutations(range(1,n+1)))
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
aans = 0
bans = 0
for i in s:
  if a == i:
    aans = s.index(a)
  if b == i:
    bans = s.index(b)
print(abs(aans-bans))

Solution (Python):
import sys
import math
import bisect
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop


def LI(): return [int(x) for x in sys.stdin.readline().split()]


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


def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res


def IR(n):
    return [I() for i in range(n)]



def A():
    K, X = LI()
    if K * 500 >= X:
        print("Yes")
    else:
        print("No")
    return



def B():
    n = I()
    s = S()
    cnt = 0
    for i in range(n - 2):
        if s[i] == "A":
            if s[i + 1] == "B" and s[i + 2] == "C":
                cnt += 1
    print(cnt)
    return



def C():
    n = I()
    p = LI()
    q = LI()
    a_cnt = [1] * n
    b_cnt = [1] * n
    a = 0
    b = 0
    for i in range(1, n + 1):
        num = 1
        for j in range(1, n + 1 - i):
            num *= j
        a += sum(a_cnt[:p[i - 1]]) * num
        b += sum(b_cnt[:q[i - 1]]) * num
        a_cnt[p[i - 1] - 1] = 0
        b_cnt[q[i - 1] - 1] = 0
    print(abs(a - b))
    return



def D():
    return



def E():
    return



def F():
    return



if __name__ == "__main__":
    C()

Solution (Python):
import math
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
def calc(P):
    data = list(range(0,len(P)))
    re = 0
    for i in range(len(P)):
        if data[P[i] - 1] > 0:
            re += data[P[i] -1]*math.factorial(len(P) - 1 -i)
        for j in range(P[i] - 1, len(P)):
            data[j] -= 1
    return re
a = calc(P)
b = calc(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()))

num_list = list(range(1,N+1))

a = 0
b = 0
index = 0
for v in permutations(num_list,N):
    if v == P:
        a = index
    if v == Q:
        b = index

    index += 1

print(abs(a-b))

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



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


pi = 0
qi = 0
for i in range(0,len(E)):
    if p == list(E[i]):
        pi = i
        
    if q == list(E[i]):
        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()))
L=[]
R=[]
ans=0
p,q=0,0
cntp,cntq=0,0
for i in range(n):
  L.append(i+1)
  R.append(i+1)
  

for i in range(n):
    for j in L:
        if P[i] > j:
            cntp += 1
    for j in R:
        if Q[i] > j:
            cntq += 1
            
    p+=cntp*math.factorial(n-i-1)
    q+=cntq*math.factorial(n-i-1)
   
    L.remove(P[i])
    R.remove(Q[i])
    cntp,cntq=0,0
print(abs(p-q))

Solution (Python):
from itertools import permutations

n = int(input())
pi = list(map(int, input().split()))
qi = list(map(int, input().split()))

for i, p in enumerate(permutations(list(range(1,n+1)))):
    if "".join(map(str, pi)) == "".join(map(str, p)):
        a = i+1
    if "".join(map(str, qi)) == "".join(map(str, p)):
        b = i+1
print(abs(a-b))

Solution (Python):

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

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

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

Solution (Python):
N = int(input())
nums1 = list(map(int, input().split()))
nums2 = list(map(int, input().split()))
r1 = 1
r2 = 1
def getOrder(nums):
    r = 1
    base = 1
    for i in range(N):
        base *= (i + 1)
    for idx in range(N):
        base //= (N - idx)
        s = {n: i for i, n in enumerate(sorted(nums[idx:]))}
        orders = [s[i] for i in nums[idx:]]
        r += orders[0] * base
    return r
a = (getOrder(nums1))
b = (getOrder(nums2))
print(abs(a - b))

Solution (Python):
import math

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

ansp=1
ansq=1

for i in range(n):
    count=0
    for j in range(i+1,n):
        if p[i]>p[j]:
            count+=1
    ansp+=count*math.factorial(n-i-1)

for i in range(n):
    count=0
    for j in range(i+1,n):
        if q[i]>q[j]:
            count+=1
    ansq+=count*math.factorial(n-i-1)
print(abs(ansp-ansq))

Solution (Python):
from itertools import permutations 

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

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

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

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

Solution (Python):
from itertools import permutations
N = int(input())
P = "".join(list(map(str,input().split())))
Q = "".join(list(map(str,input().split())))
ls = permutations(list(range(1,N+1)))
ans = []
for i in list(ls):
    ans.append("".join(list(map(str,i))))
ans = sorted(ans)
a,b = 0,0
for i in range(len(ans)):
    if ans[i] == P:
        a = i+1
    if ans[i] == Q:
        b = i+1
print(abs(int(a)-int(b)))

Solution (Python):
import itertools

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

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

a = full_list.index(p) + 1
b = full_list.index(q) + 1
print(abs(a-b))

Solution (Python):
import itertools

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

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

p_i = comb.index(p)
q_i = comb.index(q)

print(abs(p_i-q_i))

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

Solution (Python):
from itertools import permutations as p


def main():
    N = int(input())
    P = list(map(int, input().split(" ")))
    Q = list(map(int, input().split(" ")))
    l = []
    for i in range(1, N + 1):
        l.append(i)
    ints = []
    for k in p(l, N):
        ints.append(list(k))
    print(abs(ints.index(P) - ints.index(Q)))


if __name__ == '__main__':
    main()

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

a2=0
b2=0
seq=[]

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

an=list(itertools.permutations(seq))

c=0
while a2==0 or b2==0:
    if a==an[c]:
        a2=c+1
    
    if b==an[c]:
        b2=c+1
    
    c+=1

print(abs(a2-b2))

Solution (Python):
if __name__ == '__main__':
  from itertools import permutations
  N = int(input())
  P = input()
  P = ''.join(P.split())
  Q = input()
  Q = ''.join(Q.split())
  
  base = ''
  for i in range(N):
    base += str(i+1)
  
  perm = sorted(''.join(chars) for chars in permutations(base))
  x = -1
  y = -1
  for idx, p in enumerate(perm):
    if P == p:
      x = idx
    if Q == p:
      y = idx
    if not (x == -1) and not (y == -1):
      break
  print(abs(x-y))

Solution (Python):
from itertools import permutations 

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

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

Solution (Python):
N=int(input())
P=list(map(str,input().split()))
Q=list(map(str,input().split()))
import itertools
S="".join(map(lambda x:str(x),range(1,N+1)))
A=list(itertools.permutations(S))

P_N = 0
Q_N = 0

QQ = ()
for q in Q:
  QQ += tuple(q)
PP = ()
for p in P:
  PP += tuple(p)
ind=1
for s in A:
  if QQ == s:
    Q_N = ind
  if PP == s:
    P_N = ind
  ind += 1
print(abs(P_N - Q_N))

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

Solution (Python):
import math
import itertools


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

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

    a = 0
    b = 0

    for i in range(len(permutations)):

        if permutations[i] == P:
            a = i

        if permutations[i] == Q:
            b = i
    print(abs(a-b))


if __name__ == '__main__':
    main()

Solution (Python):
import itertools

n = int(input())
a = tuple([int(i) for i in input().split()])
b = tuple([int(i) for i in input().split()])
ai = 0
bi = 0
i = 1
val = [None] * n

for i in range(n):
    val[i] = i+1
for v in itertools.permutations(val, n):
    if v == a: ai = i-1
    if v == b: bi = i-1
    i += 1

print(abs(ai-bi))

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

def bikkuri(n):
    a=1
    for i in range(1,n+1):
        a*=i
    return a

ans=0
for i in range(n):
    pcnt=0
    qcnt=0
    for j in range(i+1,n):
        if p[i]>p[j]:
            pcnt+=1
        if q[i]>q[j]:
            qcnt+=1
    ans+=(pcnt-qcnt)*bikkuri(n-i-1)
print(abs(ans))

Solution (Python):
import itertools
import math
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
lista = [None]*n
for i in range(n):
    lista[i] = i+1
listb =[]
for i in itertools.permutations(lista):
    listb.append(i)
pp = listb.index(p)+1
qq = listb.index(q)+1
print(abs(pp-qq))

Solution (Python):
def rekkyo(n, s):
  if len(s) == n:
    rek.append(int(s))
    return
  
  for i in range(1, n+1):
    if not str(i) in s:
      rekkyo(n, s + str(i))
     
  return

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

rek = []
rekkyo(n, '')

rek.sort()
p_pos = rek.index(p)
q_pos = rek.index(q)

if p_pos < q_pos:
  ans = q_pos - p_pos
else:
  ans = p_pos - q_pos

print(ans)

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

Solution (Python):
import itertools
n = int(input())
p = list(input().split())
q = list(input().split())
p = ''.join(p)
q = ''.join(q)
n_list = [str(i) for i in range(1, n + 1)]
n_comp = list(itertools.permutations(n_list, n))
n_join = []

for i in n_comp:
    n_join.append(''.join(i))
n_join.sort()

a = 0
b = 0
for i in range(len(n_join)):
    if n_join[i] == p:
        a = i + 1
    if n_join[i] == q:
        b = i + 1
print(abs(a - b))

Solution (Python):
import math

N = int(input())
PN = list(map(int, input().split()))
QN = list(map(int, input().split()))

def listCount(_list):
    length = len(_list)

    lessList = []
    for i in range(length):
        lessCount = 0
        for j in range(i):
            if _list[i] > _list[j]:
                lessCount += 1
        lessList.append((_list[i] - 1) - lessCount)

    result = 0
    for i in range(length):
        result += (lessList[i]) * math.factorial(length-i-1)

    return result

PNCount = listCount(PN)
QNCount = listCount(QN)
print(abs(PNCount - QNCount))

Solution (Python):
import itertools

N = int(input())
P = tuple(map(lambda x: int(x) - 1, input().split()))
Q = tuple(map(lambda x: int(x) - 1, input().split()))

a = None
c = 0
for x in itertools.permutations(range(N), N):
    c += 1
    if x == P:
        if a is None:
            a = c
        else:
            print(abs(a - c))
            exit()
    if x == Q:
        if a is None:
            a = c
        else:
            print(abs(a - c))
            exit()

Solution (Python):
import itertools
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
p_count = 0
q_count = 0
count = 0
k = []
for i in range(N):
    k.append(i+1)
for i in itertools.permutations(k,N):
    count += 1
    if i == P:
        p_count = count
    if i == Q:
        q_count = count

sum = abs(p_count-q_count)
print(sum)

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

a = 0
b = 0
nums = list(range(N+1)[1:])
for i, p in enumerate(P):
  if i+1 == N:
    break
  a += math.factorial(N-1-i) * (nums.index(p)) + 1
  nums.pop(nums.index(p))

nums = list(range(N+1)[1:])
for i, q in enumerate(Q):
  if i+1 == N:
    break
  b += math.factorial(N-1-i) * (nums.index(q)) + 1
  nums.pop(nums.index(q))

print(abs(a-b))

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

def order(l):
    ans=0
    a=list(range(N))
    for i in range(N):
        ans+= a[l[i]-1]*math.factorial(N-1-i)
        for j in range(l[i],N):
            a[j]-=1
    return ans
p=order(P)
q=order(Q)
print(abs(p-q))

Solution (Python):
import sys
from collections import deque
input = sys.stdin.readline

def reorder(que, v):
  for i in range(len(que)):
    if que[i] > v:
      que[i] -= 1
  return que

def factorial(n):
  if n > 1:
    return n * factorial(n-1)
  return 1

def get_order(que):
  n = 0
  while(que):
    q = que.popleft()
    n += ((q-1) * factorial(len(que)))
    que = reorder(que, q)
  return n

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

n = get_order(P)
m = get_order(Q)
print(abs(n-m))

Solution (Python):
from itertools import permutations 

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

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

Solution (Python):
import itertools

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

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

database = list(itertools.permutations(N_list))

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

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

N = int(input())
P = tuple([int(i) for i in input().split()][0:N])
Q = tuple([int(i) for i in input().split()][0:N])
l = list(itertools.permutations(range(1,N+1)))
print(abs(l.index(Q) - l.index(P)))

Solution (Python):
import itertools

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

if p_list == q_list:
	print(0)
else:
	a, b = 0, 0
	permutation = list(itertools.permutations(range(1,n+1)))
	for i, p in enumerate(permutation):
		pl = list(p)
		if pl == p_list:
			a = i
		elif pl == q_list:
			b = i
	print(abs(a-b))

Solution (Python):
def p_(val):
    ret = 1
    for i in range(2, val+1):
        ret *= i
    return ret


def func(n, val):
    l = [j for j in range(1, n+1)]
    idx = 0
    for i, val_i in enumerate(val[:-1]):
        idx += (l.index(val_i)) * p_(n - 1 - i)
        l.pop(l.index(val_i))
    return idx


n = int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
print(abs(func(n, p) - func(n, q)))

Solution (Python):
from sys import stdin
import math

N = int(stdin.readline().rstrip())
P = [int(x) for x in stdin.readline().rstrip().split()]
Q = [int(x) for x in stdin.readline().rstrip().split()]
rp = [int(x + 1) for x in range(N)]
rq = [int(x + 1) for x in range(N)]

index_p = 0
index_q = 0

for i in range(N):
    index_p += math.factorial(N - i - 1) * (rp.index(P[i]) - 1)
    index_q += math.factorial(N - i - 1) * (rq.index(Q[i]) - 1)
    rp.remove(P[i])
    rq.remove(Q[i])

print(abs(index_p - index_q))

Solution (Python):
import itertools
import copy
import math

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

Psorted = copy.copy(P)
Psorted.sort()
PQList = list(itertools.permutations(Psorted))

a = 0
b = 0
for i in range(math.factorial(N)):
    if PQList[i] == tuple(P):
        a = i + 1
    if PQList[i] == tuple(Q):
        b = i + 1
res = a - b
if res < 0:
    res *= -1

print(res)

Solution (Python):
import itertools

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

list = []
numList = []

for i in range(N + 1):
  if i == 0:
    continue
  numList.append(i)
  
for x in itertools.permutations(numList):
  list.append(x)

a = 0
b = 0

for index, t in enumerate(list):
  if t == P:
    a = index + 1
  
  if t == Q:
    b = index + 1

print(abs(a - b))

Solution (Python):
import itertools
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
nn = [i+1 for i in range(n)]
mm = list(itertools.permutations(nn))
print(max((mm.index(q)) - (mm.index(p)) , (mm.index(p)) - mm.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):
import math
n=int(input())
s=list(map(int,input().split()))
t=list(map(int,input().split()))
a=0
b=0
suuzi1=[i for i in range(1,n+1)]
suuzi2=[i for i in range(1,n+1)]
for i in range(n):
    a+=suuzi1.index(s[i])*math.factorial(n-i-1)
    suuzi1.remove(s[i])
for i in range(n):
    b+=suuzi2.index(t[i])*math.factorial(n-i-1)
    suuzi2.remove(t[i])
print(abs(b-a))

Solution (Python):
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
factorial = [1,2,6,24,120,720,5040,40320] 

a = [i for i in range(1,n+1)]
cnt = 0
for i in range(n):
    if i == 0:
        cnt += (p[0]-1)*factorial[(n-i-1)-1]
        a.remove(p[0])
    else:
        if a.index(p[i]) == 0:
            if i == n-1:
                cnt += 1 
        else:
            cnt += a.index(p[i]) * factorial[(n-i-1)-1]
        a.remove(p[i])
a = [i for i in range(1,n+1)]
cnt_q = 0
for i in range(n):
    if i == 0:
        cnt_q += (q[0]-1)*factorial[(n-i-1)-1]
        a.remove(q[0])
    else:
        if a.index(q[i]) == 0:
            if i == n-1:
                cnt_q += 1 
        else:
            cnt_q += a.index(q[i]) * factorial[(n-i-1)-1]
        a.remove(q[i])
print(abs(cnt-cnt_q))

Solution (Python):
import itertools
n = int(input())
p = input().replace(' ', '')
q = input().replace(' ', '')

for i, num in enumerate(itertools.permutations(range(1,n+1))):
    num = ''.join(map(str, list(num)))
    if num == p:
        break
for j, num in enumerate(itertools.permutations(range(1,n+1))):
    num = ''.join(map(str, list(num)))
    if num == q:
        break

print(abs(i-j))

Solution (Python):
from itertools import permutations 

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

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

Solution (Python):
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
if p==q:
  print(0)
  exit()
op=[i for i in range(1,n+1)]
oq=op[:]
r=[5040,720,120,24,6,2,1][8-n:]
a,b=1,1
for i in range(n-1):
  a+=op.index(p[i])*r[i]
  b+=oq.index(q[i])*r[i]
  op.remove(p[i])
  oq.remove(q[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()))

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

Solution (Python):
import itertools
import math
n = int(input())
p  = list(map(int, input().split()))
q  = list(map(int, input().split()))
lst = []
for i in range(1, n+1):
    lst.append(i)
a =  list(itertools.permutations(lst))
p_c = a.index(tuple(p))
q_c = a.index(tuple(q))
print(int(math.fabs(q_c-p_c)))

Solution (Python):
import itertools

N = int(input())
P = [int(x) for x in input().split(" ")]
Q = [int(x) for x in input().split(" ")]
l = [x for x in range(1, N + 1)]
p = itertools.permutations(l, N)

P = tuple(P)
Q = tuple(Q)
p_index = 0
q_index = 0
for index, v in enumerate(p):
    if v == P:
        p_index = index
    if v == Q:
        q_index = index

print(abs(p_index - q_index))

Solution (Python):
import itertools

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

if P == Q:
    ans = 0
else:
    PQ = [P] + [Q]
    PQ = sorted(PQ)

    li = list(range(N))
    li = list(map(lambda x: x + 1, li))

    i = 0
    j = 0
    a = []
    for v in itertools.permutations(li, N):
        j += 1
        if PQ[i] == v:
            a.append(j)
            if i == 1:
                break
            else:
                i += 1

    ans = a[1] - a[0]

print(ans)

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


P = int(input().strip().replace(" ", ""))
Q = int(input().strip().replace(" ", ""))

import itertools

seq = [str(i) for i in range(1,N+1)]
alllist = sorted([int("".join(l)) for l in list(itertools.permutations(seq))])
print(abs(alllist.index(P)-alllist.index(Q)))

Solution (Python):
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

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

PP = tuple(inpl())
QQ = tuple(inpl())

a = kakuran.index(PP)
b = kakuran.index(QQ)

print(abs(a-b))

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

seq = range(1,N+1)
Nlist=list(itertools.permutations(seq))
for index,lists in enumerate(Nlist):
    if lists == P:
        a = index
        break

for index,lists in enumerate(Nlist):
    if lists == Q:
        b = index
        break

print(abs(a-b))

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

a = 0
b = 0
c = 1
for v in itertools.permutations(ls, n):
    if list(v) == p:
        a = c
    if list(v) == q:
        b = c
    c += 1
    
print(abs(a-b))

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

def f(li,a):
    li2=[]
    for j in range(len(li)):
        for i in range(len(li[j])+1):
            li2.append(li[j][i:]+[a]+li[j][:i])
    return li2


li=[[1]]

for i in range(2,n+1):
    li=f(li,i)
    
li.sort()


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

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

Solution (Python):
import itertools

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

P = tuple(map(int,P))
Q = tuple(map(int,Q))

list_N = list(range(N))
list_N.append(N)
list_N.remove(0)
list_all = []

for i in itertools.permutations(list_N): 
    list_all.append(i)

a = (list_all.index(P)) + 1
b = (list_all.index(Q)) + 1

print(abs(a-b))

Solution (Python):
import math
n=int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
a=0
b=0
x=[i+1 for i in range(n)]
y=[i+1 for i in range(n)]

for i in range(n-1):
    a+=x.index(p[i])*math.factorial(n-1-i)
    b+=y.index(q[i])*math.factorial(n-1-i)
    x.remove(p[i])
    y.remove(q[i])


print(abs(a-b))

Solution (Python):
import itertools
n = input()
p = "".join(input().split())
q = "".join(input().split())
availables = ["".join(t) for t in list(itertools.permutations([str(i+1) for i in range(int(n))]))]
idx_p = availables.index(p)
idx_q = availables.index(q)
print(abs(idx_p-idx_q))

Solution (Python):
import itertools


def main():
    n = int(input())
    p = [int(i) for i in input().split()]
    q = [int(i) for i in input().split()]

    a = 0
    for i, p_per in enumerate(sorted(itertools.permutations(range(1, n+1))), start=1):
        if list(p_per) == p:
            a = i

    b = 0
    for j, q_per in enumerate(sorted(itertools.permutations(range(1, n+1))), start=1):
        if list(q_per) == q:
            b = j

    print(abs(a - b))


if __name__ == "__main__":
    main()

Solution (Python):
from math import factorial as ft

N = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]

num = [1 for i in range(1,N+1)]
t1 = 0
for a in range(len(p)):
    t1 += ft(N-a-1)*num[:p[a]].count(1)
    num[p[a]-1] = 0
    


num = [1 for i in range(1,N+1)]
t2 = 0
for a in range(len(q)):
    t2 += ft(N-a-1)*num[:q[a]].count(1)
    num[q[a]-1] = 0
    

print(abs(t1-t2))

Solution (Python):

import math
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
a=0
b=0
maxlist=[]
for i in range(N):
    maxlist.append(P[i])
    maxlist.sort()
    temp=maxlist.index(P[i])-1
    a=a+math.factorial(N-1-i)*(P[i]-1-temp)
maxlist=[]
for i in range(N):
    maxlist.append(Q[i])
    maxlist.sort()
    temp=maxlist.index(Q[i])-1
    b=b+math.factorial(N-1-i)*(Q[i]-1-temp)
print(max(a-b,b-a))