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 dfs(l,N):
    if len(l)==N:
        x.append(int("".join(map(str,l))))
        return
    else:
        for n in range(1,N+1):
            if n not in l:
                l.append(n)
                dfs(l,N)
                l.pop()

def main():
    N=int(input())
    P=list(input().strip().split())
    Q=list(input().strip().split())
    global x
    x=[]
    dfs([],N)
    x.sort()
    a=x.index(int("".join(P)))
    b=x.index(int("".join(Q)))
    return abs(a-b)

if __name__=="__main__":
    print(main())

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

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

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

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

lis = [x + 1 for x in range(N)] 
permutations_lis = itertools.permutations(lis)

p = 0
q = 0
if P == Q:
  ans = 0
  print(ans)
  quit()
  
x = 0
for one_case in permutations_lis: 
  x += 1
  if P == list(one_case):
    p = x
  elif Q == list(one_case):
    q = x

print(abs(q-p))

Solution (Python):
from math import factorial
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
P_0 = list(range(1, N + 1))
Q_0 = list(range(1, N + 1))
num_P = 0
num_Q = 0
for i in range(N):
  for j in range(N):
    if P[i] == P_0[j]:
      num_P += j * factorial(N - 1 - i)
      P_0.remove(P_0[j])
      break
for i in range(N):
  for j in range(N):
    if Q[i] == Q_0[j]:
      num_Q += j * factorial(N - 1 - i)
      Q_0.remove(Q_0[j])
      break
print(abs(num_Q - num_P))

Solution (Python):
from math import factorial
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
P_0 = list(range(1, N + 1))
Q_0 = list(range(1, N + 1))
num_P = 0
num_Q = 0
for i in range(N):
  for j in range(N):
    if P[i] == P_0[j]:
      num_P += j * factorial(N - 1 - i)
      P_0.remove(P_0[j])
      break
for i in range(N):
  for j in range(N):
    if Q[i] == Q_0[j]:
      num_Q += j * factorial(N - 1 - i)
      Q_0.remove(Q_0[j])
      break
print(abs(num_Q - num_P))

Solution (Python):

def main():
    n, = map(int, input().split())
    pp = tuple(map(int, input().split()))
    qq = tuple(map(int, input().split()))

    from itertools import permutations

    a, b = 0, 0
    for i, cc in enumerate(permutations(range(1, n+1), n)):
        if cc == pp:
            a = i + 1
        if cc == qq:
            b = i + 1
        if a and b:
            break

    print(abs(a - b))


if __name__ == "__main__":
    main()

Solution (Python):
import itertools
import sys
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
x = [i+1 for i in range(n)]
ans = 0
c = 1

if p == q:
  print(0)
  sys.exit()
for j in itertools.permutations(x,n):
    y = list(j)
    if p == y:
       ans += c
    elif q == y:
        ans -= c
    
    c += 1

print(abs(ans))

Solution (Python):
N=int(input())
P=tuple(map(str,input().split()))
Q=tuple(map(str,input().split()))
count=0
a,b=0,0
import itertools
if P==Q:
    print(0)
else:
    for i in itertools.permutations(sorted(P),len(P)):
        count+=1
        if i==P:
            a=count
        elif i==Q:
            b=count
    print(abs(a-b))

Solution (Python):
import sys

readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
read = sys.stdin.buffer.read
sys.setrecursionlimit(10 ** 7)
INF = float('inf')

import itertools

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

per = itertools.permutations(range(1, N+1))
for i, seq in enumerate(per):
    if seq == P:
        p_index = i + 1
    if seq == Q:
        q_index = i + 1

ans = abs(p_index - q_index)
print(ans)

Solution (Python):
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

n=ni()
p=nl()
q=nl()

cnt=0

pnum=0
qnum=0

def comb(nums):
  global cnt
  global pnum
  global qnum
  if len(nums)==n:
    cnt+=1
    if nums == p:
      pnum = cnt
    if nums == q:
      qnum = cnt
    return
  for i in range(1,n+1):
    if i not in nums:
      comb(nums+[i])


comb([])

print(abs(pnum-qnum))

Solution (Python):
import sys
import math
import itertools
import numpy

rl = sys.stdin.readline

r = int(rl())
n1 = tuple(map(int, rl().split()))
n2 = tuple(map(int, rl().split()))
li = list(itertools.permutations(range(1, r+1)))
print(abs(li.index(n1) - li.index(n2)))

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

import itertools

A = list(itertools.permutations(list(range(1, n+1))))
 
a = A.index(tuple(P))
b = A.index(tuple(Q))
print(abs(a-b))

Solution (Python):
import itertools

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

t = [num for num in range(1, n+1)]
a = []
per_c = 0

for per in itertools.permutations(t):
  s = ''
  for i in range(n):
    s += str(per[i])
  a.append(int(s))
a.sort()



p_i = 0
q_i = 0
for i in range(len(a)):
  b = a[i]
  if b == p:
    p_i = i+1
  if b == q:
    q_i = i+1

print(abs(p_i - q_i))

Solution (Python):
import itertools

n = int(input())
c1 = tuple(map(int,input().split()))
c2 = tuple(map(int,input().split()))
a = []
for i in range(n):
    a.append(i + 1)

b=list(itertools.permutations(a))

for i in range(len(b)):
    if(c1 == b[i]):
        k1 = i
    if(c2 == b[i]):
        k2 = i
    

ans = abs(k1 -k2)
print(ans)

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

from itertools import permutations
per = permutations(list(map(str, range(1,n+1))), n)
per = [int("".join(list(pi))) for pi in per]

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

Solution (Python):
import itertools

N = int(input())
a = list(itertools.permutations(range(1, N + 1)))
P = tuple(int(i) for i in input().split())
Q = tuple(int(i) for i in input().split())

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

Solution (Python):
from itertools import permutations

n = int(input())
p = tuple(map(str,input().split()))
q = tuple(map(str,input().split()))
s=''
for i in range(n):
    s+=str(i+1)
l=list(permutations(s,n))

for i in range(len(l)):
    if l[i]==p:
        a=i
    if l[i]==q:
        b=i
print(abs(a-b))

Solution (Python):
from itertools import permutations

N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
L = [i for i in range(1,N+1)]
p = 0
q = 0
for i, l in enumerate(permutations(L)):
    if list(l) == P:
        p = i
    if list(l) == Q:
        q = i
print(abs(p-q))

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

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

candidate = []
candidates = []

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

import itertools
for p in itertools.permutations(candidate, N):
    candidates.append(''.join(p))

candidates.sort()

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

print(str(abs(a-b)))

Solution (Python):
from itertools import permutations as p


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

permutations = ["".join(str(i) for i in iterable) for iterable in p(range(1,N+1))]

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

Solution (Python):
import itertools

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

a = None
b = None

c = 0
for x in itertools.permutations(range(1,N+1)):
  c += 1
  x = list(x)
  
  if x == P:
    a = c
  if x == Q:
    b = c
    
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()))

nums = list(permutations(range(1,n+1), n))
a = 0
b = 0
c = 0
for i in nums:
  c += 1
  if i == p:
    a = c
  if i == q:
    b = c
print(abs(a-b))

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

from itertools import permutations

l = list(range(1, n + 1))
perm = permutations(l, n)

idx_P, idx_Q = 0, 0
for i,v in enumerate(perm):
    if v == tuple(P):
        idx_P = i
    if v == tuple(Q):
        idx_Q = i

print(abs(idx_P - idx_Q))

Solution (Python):
from itertools import permutations as per
n = int(input())
pe = [i for i in range(1, n+1)]
P, Q = tuple(map(int, input().split())), tuple(map(int, input().split()))
p, q = 0, 0
for i, j in enumerate(per(pe)):
    if j==P: p = i + 1
    if j==Q: q = i + 1
print(abs(p-q))

Solution (Python):
import math
from collections import deque
from collections import defaultdict


def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()
def factorization(n):
	res = []
	if n%2==0:
		res.append(2)
	for i in range(3,math.floor(n//2)+1,2):
		if n%i==0:
			c = 0
			for j in res:
				if i%j==0:
					c=1
			if c==0:
				res.append(i)
	return res
def fact2(n):
	p = factorization(n)
	res = []
	for i in p:
		c=0
		z=n
		while 1:
			if z%i==0:
				c+=1
				z/=i
			else:
				break
		res.append([i,c])
	return res
def fact(n):
	ans = 1
	m=n
	for _i in range(n-1):
		ans*=m
		m-=1
	return ans
def comb(n,r):
	if n<r:
		return 0
	l = min(r,n-r)
	m=n
	u=1
	for _i in range(l):
		u*=m
		m-=1
	return u//fact(l)
def combmod(n,r,mod):
	return (fact(n)/fact(n-r)*pow(fact(r),mod-2,mod))%mod
def printQueue(q):
	r=copyQueue(q)
	ans=[0]*r.qsize()
	for i in range(r.qsize()-1,-1,-1):
		ans[i] = r.get()
	print(ans)
class UnionFind():
	def __init__(self, n):
		self.n = n
		self.parents = [-1]*n

	def find(self, x): 
		if self.parents[x]<0:
			return x
		else:
			self.parents[x] = self.find(self.parents[x])
			return self.parents[x]

	def union(self,x,y):
		x = self.find(x)
		y = self.find(y)

		if x==y:
			return

		if self.parents[x]>self.parents[y]:
			x,y = y,x

		self.parents[x]+=self.parents[y]
		self.parents[y]=x

	def size(self,x):
		return -1*self.parents[self.find(x)]

	def same(self,x,y):
		return self.find(x)==self.find(y)

	def members(self,x): 
		root = self.find(x)
		return [i for i in range(self.n) if self.find(i)==root]

	def roots(self):
		return [i for i,x in enumerate(self.parents) if x<0]

	def group_count(self):
		return len(self.roots())

	def all_group_members(self):
		return {r: self.members(r) for r in self.roots()} 
def bitArr(n):
	x = 1
	zero = "0"*n
	ans = []
	ans.append([0]*n)
	for i in range(2**n-1):
		ans.append(list(map(lambda x:int(x),list((zero+bin(x)[2:])[-1*n:]))))
		x+=1
	return ans;
def arrsSum(a1,a2):
	for i in range(len(a1)):
		a1[i]+=a2[i]
	return a1
def maxValue(a,b,v):
	v2 = v
	for i in range(v2,-1,-1):
		for j in range(v2//a+1): 
			k = i-a*j
			if k%b==0:
				return i
	return -1
def copyQueue(q):
	nq = queue.Queue()
	n = q.qsize()
	for i in range(n):
		x = q.get()
		q.put(x)
		nq.put(x)
	return nq

n = readInt()
p = readInts()
q = readInts()

def countmin(arr,x):
	arr.sort()
	ans = 0
	for i in range(len(arr)):
		if arr[i]<x:
			ans+=1
	return ans;

def calc(arr):
	ans=1
	ra = list(range(1,n+1))
	for i in range(n-1):
		ra.remove(arr[i])
		ans+=countmin(ra,arr[i])*fact(len(ra))
		
	return ans

def calc2():
	return abs(calc(p)-calc(q))

print(calc2())

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

Solution (Python):
n=int(input())
p=tuple(map(int,input().split()))
q=tuple(map(int,input().split()))
a=list(range(1,n+1))
import itertools
a_list=list(itertools.permutations(a))
import math
p_=0
q_=0
for i in range(math.factorial(n)):
  if p==a_list[i]:
    p_=i
  if q==a_list[i]:
    q_=i

print(abs(p_-q_))

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)]
j = list(itertools.permutations(num_list))
print(abs(j.index(p) - j.index(q)))

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

a = 0
b = 0
for i,l in enumerate(permutations([i for i in range(1,n+1)],n)):
    if list(l)==P:
        a=i
    if list(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()))

permutations = list(permutations(range(1,n+1)))

p = permutations.index(P)
q = permutations.index(Q)

print(abs(p-q))

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

Solution (Python):
from itertools import permutations

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

pi = None
qi = None
for index, numbers in enumerate(permutations(range(1, N + 1))):
    if numbers == p:
        pi = index
        if qi is not None:
            break
    if numbers == q:
        qi = index
        if pi is not None:
            break

print(abs(pi - qi))

Solution (Python):
import itertools


N = int(input())

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

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

Solution (Python):
import itertools as it

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

pe = sorted(list(it.permutations([i for i in range(1,n+1)])))

print(abs((pe.index(p)+1) - (pe.index(q)+1)))

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

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

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

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

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

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

ans_ls = list(itertools.permutations(range(1,N+1)))
P_num = ans_ls.index(tuple(P))
Q_num = ans_ls.index(tuple(Q))
print(abs(P_num-Q_num))

Solution (Python):
import itertools

n = int(input())
P = input().split()
Q = input().split()
p = ''.join(P)
q = ''.join(Q)
P.sort()
numbers = list(itertools.permutations(P))

numbers_str = []
for num in numbers:
    numbers_str.append(''.join(num))

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

Solution (Python):

"""
Created on Sun May 17 19:16:09 2020

@author: Kanaru Sato
"""
import itertools

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

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

count = 0
for perm in itertools.permutations(nums):
    count += 1
    if p == perm:
        pcount = count
    if q == perm:
        qcount = count

print(abs(pcount-qcount))

Solution (Python):
import itertools

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

Pcount = 0
Qcount = 0
counter = 1
for tmp in itertools.permutations(sorted(P)):
    if list(tmp) == P: Pcount += counter
    if list(tmp) == Q: Qcount += counter
    if Pcount != 0 and Qcount != 0: break
    else: counter += 1

print(abs(Pcount - Qcount))

Solution (Python):
import itertools

N=int(input())
seq = range(1,N+1,1)

allList=list(itertools.permutations(seq))
A=list(map(int, input().split()))
B=list(map(int, input().split()))

a = allList.index(tuple(A))
b = allList.index(tuple(B))

print(abs(a-b))

Solution (Python):
import itertools

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

it = []

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

retu = list(itertools.permutations(it))

result = abs(retu.index(P)-retu.index(Q))

print(result)

Solution (Python):
in_num = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
import itertools
ans = [list(j) for j in list(itertools.permutations([i+1 for i in range(in_num)]))]
import math
print(int(math.fabs(ans.index(P) - ans.index(Q))))

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

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

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

Solution (Python):
import itertools
n=int(input())
l=[i+1 for i in range(n)]
p=[int(x) for x in input().rstrip().split()]
q=[int(x) for x in input().rstrip().split()]

cnt=0
ans_l=[]
for pq in itertools.permutations(l):
  ans_l.append(list(pq))

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

Solution (Python):
import itertools
import math

n = int(input())
word = [[int(i)  for i in input().split()] for j in range(2)]

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

count = 0
a = 0
b = 0
for one_case in permutations_lis:
    count += 1
    if(list(one_case) == word[0]):
        a = count
    if(list(one_case) == word[1]):
        b = count

print(abs(a-b))

Solution (Python):
import itertools
N = int(input())
NL = [str(i) for i in range(1,N+1)]
P = input().replace(' ', '')
Q = input().replace(' ', '')
NLL = sorted(list(itertools.permutations(NL,N)))
a = 0
b = 0
for i in range(len(NLL)):
    if ''.join(list(NLL[i])) == P:
        a = i+1
    if ''.join(list(NLL[i])) == Q:
        b = i+1
print(abs(a-b))

Solution (Python):
n=int(input())
a=[0]*n
b=[0]*n
a[:]=map(int,input().split())
import itertools
c=list(itertools.permutations(a, n))
c.sort()
b[:]=map(int,input().split())
a=tuple(a)
b=tuple(b)
"""
print(a)
print(b)
print(c)
"""
print(abs(c.index(a)-c.index(b)))

Solution (Python):
import itertools

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

a = [i+1 for i in range(n)]
l = list(itertools.permutations(a))
count = 0
for i in l:
    if p == list(i):
        p_num = count
    if q == list(i):
        q_num = count
    count+=1
if p_num >= q_num:
    print(p_num-q_num)
else:
    print(q_num-p_num)

Solution (Python):
import itertools

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

nums = []
for i in range(N):
    nums.append(i + 1)
S = list(itertools.permutations(nums))

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

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

def nc(i):
  if i==1 or i==0:
    return 1
  else :
    return nc(i-1)*i

def check(A):
  l=len(A)
  if l==1:
    return 1
  tar=A[0]
  t=0
  for a in A[1:]:
    if tar > a:
      t+=1
  A.pop(0)
  return t*nc(l-1)+check(A)

cp=check(p)
cq=check(q)
d=cp-cq
if d<0:
  d=d*(-1)

print(d)

Solution (Python):
import sys
import itertools
stdin = sys.stdin

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

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

N_l=list(itertools.permutations(list(range(1,N+1))))
N_l=N_l[::-1]

P_inds=N_l.index(tuple(P))
Q_inds=N_l.index(tuple(Q))

print(abs(P_inds-Q_inds))

Solution (Python):
import sys
import itertools


input = sys.stdin.readline


def main():
    a, b = -1, -1
    count = 0
    for p in itertools.permutations(range(1, N+1)):
        if p == P:
            a = count
        if p == Q:
            b = count
        if a != -1 and b != -1:
            break
        count += 1
    print(abs(a-b))


if __name__ == "__main__":
    N = int(input())
    P = tuple([int(p) for p in input().split()])
    Q = tuple([int(q) for q in input().split()])
    main()

Solution (Python):
import itertools

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

li = []
for i in range(N):
    li.append(i+1)
l2 = list(itertools.permutations(li))

gap = abs(l2.index(P_t) - l2.index(Q_t))
print(gap)

Solution (Python):
import math

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

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

print(abs(p-q))

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

Solution (Python):
from itertools import permutations

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

for i, can in enumerate(permutations(range(1, n+1))):
    if p == can:
        x = i
    if q == can:
        y = i
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()))

cnt = 0
for l in permutations(range(1,n+1),n):
    cnt+=1
    if(l==p):
        a=cnt
    if(l==q):
        b=cnt
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())

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

print("{}".format(abs(permutations.index(P) - permutations.index(Q))))

Solution (Python):
import itertools
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
cnt = 1
p = 0
q = 0
for n in itertools.permutations(range(1, N+1)):
    if P == list(n):
        p = cnt
    if Q == list(n):
        q = cnt
    cnt += 1
total = abs(p-q)
print(total)

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

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

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

print(abs(a-b))

Solution (Python):
import itertools as ite

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

ps = ite.permutations([i for i in range(1,n+1)])

for i,ele in enumerate(ps):
    if ele==p: a = i
    if ele==q: b = i

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

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

Solution (Python):
import itertools

N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
m = itertools.permutations(range(1,N+1))

P_id = 0
Q_id = 0

for i,l in enumerate(m):
  if l == tuple(P):
    P_id = i
  if l == tuple(Q):
    Q_id = i

    
print(abs(Q_id - P_id))

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

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

for i, L in enumerate(lst):
    
    if L == tuple(P):
        a = i + 1
    if L == tuple(Q):
        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()))

a,b = 0,0
flag = 0

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

if (p != q):
    for i in range(len(ix)):
        t = list(ix[i])
        if (p == t):
            a = i
            flag += 1
        elif (q == t):
            b = i
            flag += 1
        if (flag == 2):
            break
print(abs(a-b))

Solution (Python):
import itertools
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)
n_lst=list(itertools.permutations(l,n))
a=n_lst.index(tuple(p))
b=n_lst.index(tuple(q))
print(abs(a-b))

Solution (Python):
from itertools import permutations
n=int(input())
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
a1=sorted(a)
b1=sorted(b)
a2=list(permutations(a1))
b2=list(permutations(b1))
ans1=a2.index(tuple(a))
ans2=b2.index(tuple(b))
print(abs(ans1-ans2))

Solution (Python):
import itertools

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

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

for i in range(len(per)):
    if per[i]==p:
        a = i+1
    if per[i]==q:
        b = i+1

print(abs(a-b))

Solution (Python):
import itertools

n=int(input())
data=[x+1 for x in range(n)]
p = [int(_) for _ in input().split()]
q = [int(_) for _ in input().split()]
a=b=-1
i=0
for d in itertools.permutations(data):
  if list(d)==p:
    a=i
  if list(d)==q:
    b=i
  
  i+=1
    
print(abs(a-b))

Solution (Python):
import itertools

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

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

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

Solution (Python):

import sys
import time
import unittest
from io import StringIO
import itertools


def resolve():
    N = int(input())
    P = [int(i) for i in input().split()]
    Q = [int(i) for i in input().split()]
    a = 0
    b = 0
    i = 0
    for s in itertools.permutations(range(1, N + 1)):
        if a == 0 and tuple(s) == tuple(P):
            a = i + 1
        if b == 0 and tuple(s) == tuple(Q):
            b = i + 1
        i += 1
    print(abs(a - b))


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def setUp(self):
        self.startTime = time.time()

    def tearDown(self):
        t = time.time() - self.startTime
        print('%s: %.3f' % (self.id(), t), flush=True)

    def test_入力例_1(self):
        input = """3
1 3 2
3 1 2"""
        output = """3"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1"""
        output = """17517"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """3
1 2 3
1 2 3"""
        output = """0"""
        self.assertIO(input, output)


if __name__ == "__main__":
    if "IS_LOCAL" in locals():
        suite = unittest.TestLoader().loadTestsFromTestCase(TestClass)
        unittest.TextTestRunner(verbosity=0).run(suite)
    else:
        resolve()

Solution (Python):
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]

n=n0()
p=n1()
q=n1()

import itertools
ite=list(itertools.permutations(range(1,n+1)))
a=ite.index(tuple(p))
b=ite.index(tuple(q))
print(abs(a-b))

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

n_list = []
for i in range(1,n+1):
    n_list.append(i)
    
p_position = 0
for j in itertools.permutations(n_list, n):
    p_position += 1
    if tuple(p) != j:
        continue
    else:
        break

q_position = 0
for j in itertools.permutations(n_list, n):
    q_position += 1
    if tuple(q) != j:
        continue
    else:
        break
        
if p_position > q_position:
    print(p_position-q_position)
else:
    print(q_position-p_position)

Solution (Python):
import itertools

n=int(input())
list_a = list(map(int,input().split()))
list_b = list(map(int,input().split()))

list_0 = list(range(1, n+1))


i = 1
a = 0
b = 0
for v in itertools.permutations(list_0):
  if list(v) == list_a:
    a = i
  if list(v) == list_b:
    b = i
  i += 1
print(abs(a-b))

Solution (Python):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
import itertools
list_all = itertools.permutations (range(1, N+1))

for i, L in enumerate(list_all):
    if L == tuple(P):
        a = i + 1
    if L == tuple(Q):
        b = i + 1
print(abs(a-b))