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 itertools import permutations
def main():
    N=int(input())
    P=tuple(int(_) for _ in input().split())
    Q=tuple(int(_) for _ in input().split())
    if P==Q:
        print(0)
        exit()
    ans=[0,0]
    cnt=1
    using=tuple(map(int,range(1,N+1)))
    for i,a in enumerate(list(permutations(using, N))):
        if a==P:
            ans[0]=cnt
        elif a==Q:
            ans[1]=cnt
        if ans[0]!=0 and ans[1]!=0:
            print(abs(ans[0]-ans[1]))
            exit()
        cnt+=1

main()

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

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

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

Solution (Python):
import sys
import os
import math
import bisect
import collections
import itertools
import heapq

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: x * y / math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    P = il()
    Q = il()
    pt, qt = [], []

    for p in itertools.permutations(P):
        pt.append(p)
    for q in itertools.permutations(Q):
        qt.append(q)
    pc = sorted(pt).index(tuple(P)) + 1
    qc = sorted(qt).index(tuple(Q)) + 1
    print(abs(pc - qc))


if __name__ == '__main__':
    main()

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

Solution (Python):
from functools import reduce
from operator import mul

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


def kaidan(n):
    return reduce(mul, range(1,n+1))

def migi(i,A):
    return len( list(filter(lambda x: x < A[i], A[i+1:])) )

def num(A):
    s = 0
    for i in range(N-1):
        s += kaidan(N-1-i) * migi(i,A)
    return s

print(abs(num(P) - num(Q)))

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)))
ans2=-1

for n in range(len(a)):
  if a[n]==P:
    ans1=n
  elif a[n]==Q:
    ans2=n
if ans2 != -1:
  print(abs(ans1-ans2))
else:
  print(0)

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

xy_list = list()

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



A = tuple( i+1 for i in range(N) )


from itertools import permutations
A_perm = list(permutations(A, N) )



p_num = N*2 
q_num = N*2 


for i, a in enumerate(A_perm):
    if tuple(a) == P:
        p_num = i
    if tuple(a) == Q:
        q_num = i

print(abs(q_num-p_num))

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

Solution (Python):
import math

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


def fun(x):
    
    count=0
    
    for k in range(len(x)-1):
        count+=math.factorial(len(x)-1)*sum(i<x[0] for i in x)
        del x[0]
        
    return count+1

a=fun(p)
b=fun(q)

print(int(abs(a-b)))

Solution (Python):
import itertools
import math

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

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

print(abs(a - b))

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

p_mojiretu = ""
q_mojiretu = ""

for x in p:
    p_mojiretu += x
for x in q:
    q_mojiretu += x


cnt = 1
index_a = 0
index_b = 0

for i in itertools.permutations(range(1, n+1)):
    s = "".join(str(x) for x in i)
    if s == p_mojiretu:
        index_a = cnt
    if s == q_mojiretu:
        index_b = cnt
    cnt += 1
print(abs(index_a - index_b))

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

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




p_num = 0
q_num = 0



for i in range(math.factorial(n)):
    
    if s[i] == p:
        p_num = i

    if s[i] == 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())
h=[]
for i in range(n):
    h+=str(i+1)
k=list(itertools.permutations(h))
p2=-1
q2=-1
for i in range(len(k)):
    if p==k[i]:
        p2=i
    if q==k[i]:
        q2=i
    if p2 != -1 and q2 !=-1:
        break
print(abs(p2-q2))

Solution (Python):

import sys

readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return tuple(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))


n = readint()
p = readints()
q = readints()

from itertools import permutations

a = 0
b = 0

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

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

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

cur = []
for i in permutations(range(1, n + 1)):
    copy = []
    for u in i:
        copy.append(u)
    cur.append(str(copy))

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

Solution (Python):
from itertools import permutations
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
l=[i for i in range(1,n+1)]
L=list(map(list,permutations(l)))
vp=L.index(p)
vq=L.index(q)
print(abs(vp-vq))

Solution (Python):
from itertools import permutations
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
cnt = 1
for num in permutations(range(1,n+1)):
    cnt += 1
    if list(num) == p:
        p_num = cnt
    if list(num) == q:
        q_num = cnt
print(abs(q_num-p_num))

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

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

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

p = 0
q = 0
for i in range(len(per)):
    if P == list(per[i]):
        p = i
    if Q == list(per[i]):
        q = i

print(abs(p - q))

Solution (Python):
import itertools


n = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
c = []
for i in range(1,n+1):
    c.append(i)
p_list = list(itertools.permutations(c, n))
c = p_list.index(tuple(q))
d = p_list.index(tuple(p))

print(abs(c-d))

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

    l = [i for i in range(1, n + 1)]
    two = []
    
    for i, v in enumerate(itertools.permutations(l)):
        tmp = 0
        for j in range(n):
            if v[j] == p[j]:
                tmp += 1
        
        if tmp == n:
            two.append(i)
        
        tmp = 0

        for j in range(n):
            if v[j] == q[j]:
                tmp += 1
        
        if tmp == n:
            two.append(i)

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

Solution (Python):
import itertools,math
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
l=list(itertools.permutations(range(1,n+1)))
for i in range(math.factorial(n)):
    if all(l[i][j]==p[j] for j in range(n)):
        pj=i
    elif all(l[i][j]==q[j] for j in range(n)):
        qj=i
    elif p==q:
        pj=0
        qj=0
        break
print(abs(pj-qj))

Solution (Python):
import itertools

def count_order(numbers, str_P, str_Q):
    p_list = list(itertools.permutations(range(numbers), numbers))
    p_index = p_list.index(str_P)
    q_index = p_list.index(str_Q)
    return abs(q_index - p_index)

if __name__ == "__main__":
    num_of_index = int(input())
    str_P = tuple([int(i) - 1 for i in input().split()])
    str_Q = tuple([int(i) - 1 for i in input().split()])
    index = count_order(num_of_index, str_P, str_Q)
    print(index)

Solution (Python):
import math

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


def fun(x):
    
    count=0
    
    for k in range(len(x)-1):
        count+=math.factorial(len(x)-1)*sum(i<x[0] for i in x)
        del x[0]
        
    return count+1

a=fun(p)
b=fun(q)

print(abs(a-b))

Solution (Python):
import math

def f(x):
    dic={}
    for a,b in enumerate(sorted(x)):
        dic[b]=a+1
    y=[]
    for i in range(len(x)):
        y.append(dic[x[i]])
    return y

def count(a):
  if len(a) ==1:
    return 1
  return (a[0]-1)*math.factorial(len(a)-1)+count(f(a[1:]))

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

print(abs(count(p)-count(q)))

Solution (Python):
N = int(input())
P = input().split()
Q = input().split()
p = [int(x) for x in P]
q = [int(x) for x in Q]
k = 1
a = 0
b = 0

for r in range(1, N):
  k *= r

for r in range(N):
  a += p[r]*k
  b += q[r]*k
  for s in range (r+1, N):
    if(p[s] > p[r]):
      p[s] -= 1
    if(q[s] > q[r]):
      q[s] -= 1
  if not N-1-r == 0:
    k /= N-1-r
  
if(b-a>=0):
  print(int(b-a))
else:
  print(int(a-b))

Solution (Python):

"""
Created on Thu May  7 03:09:14 2020

@author: Kanaru Sato
"""
import itertools as it

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

count = 0
for sequence in it.permutations(l,n):
    if list(sequence) == p:
        pnum = count
    if list(sequence) == q:
        qnum = count
    count += 1

print(abs(pnum-qnum))

Solution (Python):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
def getnum(P):
  n = 0
  l = list(range(N))
  for i in range(N):
    n *= (N-i)
    p = P[i]
    n += l[p-1]
    for j in range(p, N):
      l[j] -= 1
  return n


r = abs(getnum(P)-getnum(Q))
print(r)

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

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

Solution (Python):
import itertools
n=int(input())
pp=input().split()
qq=input().split()
p=[]
q=[]
p.append(pp)
q.append(qq)
a=[]
for v in itertools.permutations(pp,n):
    a.append(v)
a=sorted(a)
for j in range(len(a)):
  a[j]=list(a[j])

b=0
c=0
for i in range(len(a)):
  if a[i]==pp:
    b+=i
    
for k in range(len(a)):
  if a[k]==qq:
    c+=k

print(max(b-c,c-b))

Solution (Python):
import itertools
import math

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

X = sorted(P)

Y = itertools.permutations(X)

a = 0
b = 0
cnt = 1
for i in Y :
    if P == Q :
        break
    if P == i :
        a = cnt+1
    elif Q == i :
        b = cnt+1

    cnt = cnt + 1

print(abs(a-b))

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

import itertools

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

p = -1
q = -1
for i in range(len(per)):
    if P == list(per[i]):
        p = i
    if Q == list(per[i]):
        q = i

print(abs(p - q))

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

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

import itertools
a = list(itertools.permutations([i for i in range(1, n+1)]))
print(abs(a.index(p)-a.index(q)))

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from itertools import permutations, accumulate
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
import sys
def I(): return int(input())  
def Is(): return map(int, input().split())  
def LI(): return list(map(int, input().split()))  
def TI(): return tuple(map(int, input().split()))  
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()  
def LS(): return list(input())  
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(1000000)
MOD = 1000000007
INF = float('inf')

n = I()
P = LI()
p = int("".join(str(i) for i in P))
Q = LI()
q = int("".join(str(i) for i in Q))
T = []
for x in permutations(range(1, n+1), n):
    T.append(int("".join(str(i) for i in x)))

a = bisect_left(T, p)
b = bisect_left(T, 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

A = [i for i in range(1, N+1)]
lis = [l for l in permutations(A, N)]

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

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

Solution (Python):


N = int(input())
A = [str(i) for i in range(1, N + 1)]
P = ''.join([p for p in input().split()])
Q = ''.join([q for q in input().split()])

ans = []

def dfs(ls, s):
    if len(ls) == 0:
        ans.append(s)
    else:
        for i in range(len(ls)):
            dfs(ls[:i] + ls[i + 1:], s + ls[i])

dfs(A, '')
print(abs(ans.index(P) - ans.index(Q)))

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

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

x = list(itertools.permutations(range(1, n+1)))
a = x.index(tuple(p)) + 1
b = x.index(tuple(q)) + 1

print(abs(b-a))

Solution (Python):
import itertools
n=int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
count = 0
p_ind = 0
q_ind = 0
for v in itertools.permutations(sorted(p)):
    if p == list(v):
        p_ind = count + 1
    if q == list(v):
        q_ind = count + 1
    count += 1
print(abs(p_ind-q_ind))

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


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

a = []

for i in range(1,N+1):
    a += [i]
count = 1
p = 0
q = 0
for v in itertools.permutations(a, N):

    
    if list(v) == P:
        p = count
        
    if list(v) == Q:
        q = count
    
    if p > 0 and q > 0:
        break
    count+=1
        
print(abs(p-q))

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

p=tuple(map(int,input().split(" ")))
q=tuple(map(int,input().split(" ")))
for i in range(len(list)):
    if p==list[i]:
        a=i
    if q==list[i]:
        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()))

x_p = 0
x_q = 0

for i in range(N):
  x_p += p[i] * (10 ** (N - i - 1))
for i in range(N):
  x_q += q[i] * (10 ** (N - i - 1))

x_a = list(itertools.permutations(p))

x_b = list()
z = 0
for i in range(math.factorial(N)):
  for j in range(N):
    y = x_a[i][j] * (10 ** (N - j - 1))
    z += y
  x_b.append(z)
  z = 0
x_b.sort()
for i in range(math.factorial(N)):
  if x_p == x_b[i]:
    P = i + 1
for i in range(math.factorial(N)):
  if x_q == x_b[i]:
    Q = i + 1
print(abs(P - Q))

Solution (Python):


N = int(input())
P = list(int(p) for p in input().split())
Q = list(int(q) for q in input().split())

def dfs(X):
    global cnt
    global idxp
    global idxq
    if len(X)==N:
        if X==P:
            idxp = cnt
        if X==Q:
            idxq = cnt
        cnt += 1
        return
    for i in range(1, N+1):
        if i not in X:
            X.append(i)
            dfs(X)
            X.pop()

X = []
cnt = 0
idxp = 0
idxq = 0
dfs(X)

print(abs(idxp-idxq))

Solution (Python):
import itertools

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

l = [i for i in range(1, n+1)]
count = 0
pcount = -1
qcount = -1
for v in itertools.permutations(l, n):
  count += 1
  if v == p:
    pcount = count
  if v == q:
    qcount = count
  if pcount != -1 and qcount != -1:
    break

print(abs(pcount-qcount))

Solution (Python):
import itertools

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

pi = 0
qi = 0

def dfs(array, n):
  if(len(array) == n):
    return [tuple(array)]

  ret = []

  
  for i in range(1, N+1):

    if(i in array):
      continue

    array.append(i)
    ret.extend(dfs(array, n))
    array.pop()

  return ret


for index, pattern in enumerate(dfs([], N)):
  if P == pattern:
    pi = index
  if Q == pattern:
    qi = index

print(abs(pi - qi))

Solution (Python):
import itertools

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

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

pi = 0
qi = 0

for index, pattern in enumerate(patterns):
  if P == pattern:
    pi = index
  if Q == pattern:
    qi = index

print(abs(pi - qi))

Solution (Python):
from itertools import product, permutations, combinations

n = int(input())
pn = tuple(map(int, input().split(' ')))
qn = tuple(map(int, input().split(' ')))

orders = []
for i, v in enumerate(permutations(range(1, n + 1), n)):
    if v == pn:
        orders.append(i)
    if v == qn:
        orders.append(i)
        
print(abs(orders[0] - orders[1]))

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

a=0
b=0
moji=""
for i in range(1,n+1):
  i=str(i)
  moji+=i
import itertools as it
lis=list(it.permutations(moji,n))
for j in range(0,len(lis)):
  
  if lis[j]==p:
    a=j
  if lis[j]==q:
    b=j
print(abs(a-b))

Solution (Python):
import sys
from itertools import permutations
input = sys.stdin.readline


def readstr():
    return input().strip()


def readint():
    return int(input())


def readnums():
    return map(int, input().split())


def readstrs():
    return input().split()


def main():
    N = readint()
    P = tuple(readnums())
    Q = tuple(readnums())

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

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

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

print(abs(l.index(P) - l.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()))
    n_num = [i for i in range(1, n+1)]
    n_list = list(permutations(n_num, n))
    n_list.sort()
    p_pos = n_list.index(p)
    q_pos = n_list.index(q)
    print(abs(p_pos - q_pos))

if __name__ == '__main__':
    main()

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

Solution (Python):
import math
N = int(input())
P = [0] + [int(_) for _ in input().split()]
Q = [0] + [int(_) for _ in input().split()]


def d(R):
    c = [i+1 for i in range(N)]
    cnt = 0
    for i in range(1, N+1):
        idx = c.index(R[i])
        cnt += math.factorial(N - i) * idx
        del c[idx]
    return cnt


print(abs(d(P) - d(Q)))

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

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

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

a = 0
b = 0

for i in range(len(perm)):
    if p != list(perm[i]):
        a += 1
    else:
        break

for i in range(len(perm)):
    if q != list(perm[i]):
        b += 1
    else:
        break
        
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()))
per=sorted(list(permutations(p)))
print(abs(per.index(p)-per.index(q)))

Solution (Python):
import math

def findlex(a):
  max = math.factorial(len(a))
  current = 0
  current += (a[0]-1)*(max/len(a)) + lowerlex(a[0],a[1:])
  return current

def lowerlex(b,a):
  if len(a)<2:
    return 1
  else:
    max = math.factorial(len(a))
    for i in range(len(a)):
      if a[i]>b:
        a[i] -= 1
    return findlex(a)

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

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

Solution (Python):
import itertools

n = int(input())

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

a = list(itertools.permutations(range(1, n+1))).index(p)
b = list(itertools.permutations(range(1, n+1))).index(q)

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()))
N_lis = [(i + 1) for i in range(n)]
PAT = itertools.permutations(N_lis)
a, b = 0, 0
i = 0
flag = 0
for one_case in PAT:
    if P == list(one_case):
        a = i
        flag += 1
    if Q == list(one_case):
        b = i
        flag += 1
    if flag == 2:
        break
    i += 1
print(abs(a - b))

Solution (Python):
from itertools import permutations

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

for i, X in enumerate(permutations(range(1, N + 1), N)):
    if P == X:
        a = i
    if Q == X:
        b = i
print(abs(a - b))

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

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

from itertools import permutations, combinations,combinations_with_replacement,product

pcnt=0
qcnt=0
for i in permutations(a):
    if p>i:
        pcnt+=1
    if q>i:
        qcnt+=1

print(abs(pcnt-qcnt))

Solution (Python):
from itertools import permutations
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
per = list(permutations(range(1, n + 1)))
for i in range(len(per)):
    if per[i] == p:
        id_p = i
    if per[i] == q:
        id_q = i

print(abs(id_p - id_q))

Solution (Python):
import itertools

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

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

a = b = i = 0
for v in itertools.permutations(l, n):
    i += 1
    if v == p:
        a = i

    if v == q:
        b = i

print(abs(a - b))

Solution (Python):

import itertools

n = int(input())
p = 1
q = 1
a_list = list(itertools.permutations(range(1,n+1)))
for i in range(2):
    if i == 0:
        p = a_list.index(tuple(map(int,input().split())))
    else:
        q = a_list.index(tuple(map(int,input().split())))
print(abs(p - q))

Solution (Python):
import itertools

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

index = []

for i, s in enumerate(itertools.permutations(range(1, n+1),n)):
    if s == p or s == q:
        index.append(i)


if len(index) == 2:
    print(abs(index[0]-index[1]))
else:
    print('0')

Solution (Python):
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
a = 0
b = 0
c = []
for i in range(n):
    c.append(i + 1)
d = list(itertools.permutations(c))
count = 1
for lis in d:
    if p == lis:a = count
    if q == lis:b = count
    count += 1
print(abs(a - b))

Solution (Python):
import math

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

candidate = [[i] for i in range(1, N + 1)]
while len(candidate) < math.factorial(N):
    temp = []
    for c in candidate:
        for i in range(1, N + 1):
            if not i in c:
                temp.append(c + [i])
    candidate = temp

a = candidate.index(P[:-1])
b = candidate.index(Q[:-1])

print(abs(a - b))

Solution (Python):
def make(nums, now):
    
    if len(nums) == 0:
        dic.append(now)

    for i in range(len(nums)):
        tmp = nums[:i]
        if i+1 < len(nums):
            tmp += nums[i+1:]
        make(tmp, now+[nums[i]])

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
dic = []
original_nums = [i for i in range(1, n+1)]
make(original_nums, [])
for i in range(len(dic)):
    if dic[i] == p:
        num_p = i
    if dic[i] == q:
        num_q = i

print(abs(num_q - num_p))

Solution (Python):
from itertools import permutations


def main():
    N = int(input())
    P = ''.join(input().split(' '))
    Q = ''.join(input().split(' '))
    p_rank = 1
    q_rank = 1
    for perm in permutations(map(str, range(1, N + 1)), N):
        perm_str = ''.join(perm)
        if perm_str < P:
            p_rank += 1
        if perm_str < Q:
            q_rank += 1
    print(abs(p_rank - q_rank))


if __name__ == '__main__':
    main()

Solution (Python):
def main():

    import itertools
    n = int(input())
    permutation_lis = []
    a = 0
    b = 0
    ans_a = 0
    ans_b = 0

    p_lis = list(input().split())
    q_lis = list(input().split())

    permutation_lis = list(itertools.permutations(p_lis))
    permutation_lis.sort()
    

    for wordorder in permutation_lis:
        a += 1
        b += 1
        
        if p_lis == list(wordorder):
            ans_a = a
        if q_lis == list(wordorder):
            ans_b = b
    print(abs(ans_a-ans_b))




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(range(1,n+1),n))

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


print(abs(b-a))

Solution (Python):


import itertools

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


ln = list()
for i in range(1, N+1):
    ln.append(i)

all = list(itertools.permutations(ln))

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

Solution (Python):
from itertools import permutations
N = int(input())
x = tuple(map(int, input().split()))
y = tuple(map(int, input().split()))

for idx, num in enumerate(list(permutations(range(1, N+1), len(range(N)))),start=1):
    if num == x:
        a = idx
    if num == y:
        b = idx
print(abs(a-b))

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

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

Solution (Python):
import itertools

n = int(input())
x = list(map(int,input().split()))
y = list(map(int,input().split()))
li = list(range(1, n+1))
ans = []

for i in itertools.permutations(li):
    ans.append(list(i))

print(abs(ans.index(x)-ans.index(y)))

Solution (Python):
import itertools
N = int(input())
P = input().split()
Q = input().split()
N_list = []
ka = 0
kb = 0
k = 1
for i in range(1,N+1):
    N_list.append(i)

for list in itertools.permutations(N_list,N):
    for i in range(N):
        if int(P[i]) == list[i]:
            
            ka+=1
        if int(Q[i]) == list[i]:
            kb+=1
        if ka == N:
            a = k
        if kb == N:
            b = k
        
        
        
    k+=1
    ka = 0
    kb = 0
print(abs(a-b))

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

def fact(n):
  ans = n
  for i in range(1, n):
    ans *= i
  return ans

def number(lst, n):
  numlst = []
  ans = 1
  for i in range(n):
    numlst.append(i+1)
  for i in range(n):
    for j in range(len(numlst)):
      if lst[i] == numlst[j]:
        ans += j*fact(n-i-1)
        numlst.pop(j)
        break
  return ans

res = number(q, n) - number(p, n)
print(abs(res))