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):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))

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

def nasu(L):
  ans = 1
  K = [0] * (N + 1)
  for i in range(N):
    t = i + 1
    k = 0
    for j in range(1, N + 1):
      if L[i] == j: break
      if K[j] == 0:
        k += 1
    K[L[i]] = 1
    ans += k * D[N - t]
  return ans

print(abs(nasu(P) - nasu(Q)))

Solution (Python):
from itertools import permutations

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

S = [n for n in range(1, N+1)]
a = 0
b = 0

for i, p in enumerate(list(permutations(S))):
    if p == P:
        a = i + 1
    if p == Q:
        b = i + 1

print(abs(a-b))

Solution (Python):
import itertools

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

a = 0
b = 0

for i in range(len(pm)):
    if pm[i] == P:
        a = i+1
    if pm[i] == Q:
        b = i+1

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

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

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

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

from itertools import permutations

arr = list()
for i in permutations(list(range(1, N + 1)), N):
    arr.append(''.join([str(x) for x in i]))

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

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(N):
  n_list.append(i+1)

Per = list(itertools.permutations(n_list))
for i in range(len(Per)):
 tmp = list(Per[i])
 judge1,judge2 = 1,1
 for j in range(len(tmp)):
  if(tmp[j] != P[j]):
    judge1 = 0
  if(tmp[j] != Q[j]):
    judge2 = 0
    
 if(judge1 == 1): a = i+1
 if(judge2 == 1): b = 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()))

a = list(itertools.permutations([i+1 for i in range(n)], n))
ans = 0
for i in range(len(a)):
    if a[i]==p:
        ans+=i+1
    if a[i]==q:
        ans-=i+1
print(abs(ans))

Solution (Python):
import itertools

N=int(input())
P=[int(i) for i in input().split(" ")]
Q=[int(i) for i in input().split(" ")]
for i,perm in enumerate(itertools.permutations([i+1 for i in range(N)])):
    if list(perm)==P:
        a=i
    if list(perm)==Q:
        b=i

print(abs(a-b))

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

Solution (Python):
import sys
import itertools
import math
input = sys.stdin.readline
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
jisyo=[]
for i in range(1,N+1):
    jisyo.append(i)
ans =[]
for v in itertools.permutations(jisyo, N):
    ans.append(list(v))
print(abs(ans.index(P)-ans.index(Q)))

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

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

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

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

import itertools

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

Pnum=-1
Qnum=-1

for i,item in enumerate(L):
  if item==P:
    Pnum=i
  if item==Q:
    Qnum=i
  if Pnum>-1:
    if Qnum >-1:
      break

      
print(abs(Pnum-Qnum))

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

def gcd(a: int, b: int):
    """ https://cocodrips.hateblo.jp/entry/2014/03/05/143623
    """
    while b:
        a, b = b, a%b
    return a

def lcm(a: int, b: int):
    return a * b // gcd(a, b)


def main():
    N = int(input())
    
    vP = tuple(map(int, input().split()))
    vQ = tuple(map(int, input().split()))
    vA = list(range(1,N+1))

    p,q = 0,0
    for i,vI in enumerate(permutations(vA)):
        
        
        if vI==vP:
            p = i
        if vI==vQ:
            q = i
    print(abs(p-q))
    
    
    
    
    


if __name__ == "__main__":
    main()

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

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

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

x = ans.index(p)+1
y = ans.index(q)+1

if x -y >=0:
    print(x-y)
elif x-y < 0:
    print(y-x)

Solution (Python):
import itertools

N=int(input())
X=tuple(map(int,input().split()))
Y=tuple(map(int,input().split()))


L=[i for i in range(1,N+1)]
A=list(itertools.permutations(L,N))
A.sort()
x=0
y=0
for i in range(len(A)):
    if A[i]==X:
        x=i
    if A[i]==Y:
        y=i


print(abs(x-y))

Solution (Python):
def two_int():
    N, K = map(int, input().split())
    return N,K

def one_int():
    return int(input())

def one_str():
    return input()

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

import itertools as it

N= one_int()
P= many_int()
Q= many_int()

temp = list(set(P))
ans_list = list(it.permutations(temp))



first=ans_list.index(tuple([p for p in P]))

after=ans_list.index(tuple([q for q in Q]))

print(abs(after-first))

Solution (Python):
import itertools

N = int(input())
P = "".join(input().split())
Q = "".join(input().split())
L = []
for p in itertools.permutations(map(str, range(1,N+1))):
    L.append("".join(p))
L.sort()
p = -1
q = -1
i = 0
for elem in L:
    if P == elem:
        p = i
    if Q == elem:
        q = i
    i+=1
ans = abs(q-p)
print(ans)

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

Solution (Python):
import itertools

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

seq=(i for i in range(1,N+1))
All=list(itertools.permutations(seq))

for i in range(len(All)):
    if All[i]==P:
        start=i
    if All[i]==Q:
        end=i

print(abs(end-start))

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

for i, lst in enumerate(itertools.permutations(range(1,N+1))):
    if lst == P:
        p = i
    if lst == Q:
        q = i
print(abs(p-q))

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
aa=()
import itertools
c=list(itertools.permutations(range(1,n+1)))
cc=[]
for i in c:
    cc.append(list(i))
for x,i in enumerate(cc):
    if a==i:
        aa=x
    if b==i:
        bb=x
print(abs(aa-bb))

Solution (Python):
import random as rng
import itertools as it
import collections as col
import heapq as hq
import sys
import copy as cp
sys.setrecursionlimit(10**9)


def dump_impl(*objects):
    print(*objects, file=sys.stderr)


def dump_dummy(*objects):
    pass


dump = dump_impl if "DEBUG" in sys.argv else dump_dummy

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

factrials = it.permutations(range(1, N+1), N)
a = -1
b = -1
for i, fact in enumerate(it.permutations(range(1, N+1), N)):
    dump(list(zip(list(fact), P)), list(zip(list(fact), Q)))
    if all([x == y for (x, y) in zip(list(fact), P)]):
        a = i
        dump("  a=", a)
    if all([x == y for (x, y) in zip(list(fact), Q)]):
        b = i
        dump("  b=", b)
    dump(fact)
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()))

a = range(1, n+1)
t, u = 0, 0
for i, s in enumerate(permutations(a)):
    if s == p: t = i
    if s == q: u = i

print(abs(t - u))

Solution (Python):
import itertools
n = int(input())
p = list(map(int , input().split()))
q = list(map(int , input().split()))
idx = 1
a = 0
b = 0
for x in itertools.permutations(list(range(1, n+1)), n):
    if tuple(p) == x:
        a = idx
    if tuple(q) == x:
        b = idx
    idx += 1

print(abs(a-b))

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


import itertools

diff = 0
n2i = {n: i for i, n in enumerate(itertools.permutations(range(1, N + 1)))}
print(abs(n2i[P] - n2i[Q]))

Solution (Python):
from itertools import permutations
fact = [1]
N = int(input())
seq = [i for i in range(1, N+1)]
seq = list(permutations(seq))
dic = {}
for i in range(len(seq)):
  x = seq[i]
  dic[x] = i
p = tuple([int(c) for c in input().split()])
q = tuple([int(c) for c in input().split()])

P = dic[p]
Q = dic[q]
print(abs(P-Q))

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

Solution (Python):
from itertools import permutations

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

ans = 0

for i, pe in enumerate(permutations(range(1, N + 1))):
    if P == pe:
        ans += i
    if Q == pe:
        ans -= i

print(abs(ans))

Solution (Python):
import itertools


def fact_list(seq:list):
    return list(itertools.permutations(seq))


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

x = fact_list(range(1, n+1))
a = 0
b = 0
for i, xi in enumerate(x):
    if list(xi) == P:
        a = i+1
    if list(xi) == Q:
        b = i+1
print(abs(a-b))

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = [1]
for i in range(n-1):
  c = [c[0]*(i+1)] + c

A = 0
for i in range(n):
  now = a[i]
  cnt = 0
  for k in range(i+1,n):
    if a[k] < now:
      cnt += 1
  A += c[i] * cnt
B = 0
for i in range(n):
  now = b[i]
  cnt = 0
  for k in range(i+1,n):
    if b[k] < now:
      cnt += 1
  B += c[i] * cnt
print(abs(A-B))

Solution (Python):
from itertools import permutations

N = int(input())
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]

a, b = -1, -1
for i, p in enumerate(permutations(range(1, N + 1), N), 1):
    if list(p) == P:
        a = i
    if list(p) == Q:
        b = i
    if a >= 1 and b >= 1:
        break

print(abs(a - b))

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


import itertools

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

a = b = 1

for l in L:
    if l == P:
        break
    a += 1
for l in L:
    if l == Q:
        break
    b += 1
print(abs(a-b))

Solution (Python):
import sys
import itertools
import math


stdin = sys.stdin

ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split())) 
rs = lambda: stdin.readline().rstrip()  

N = ri()
P = rl()
Q = rl()
L = []
for x in itertools.permutations(range(1, N+1)):
    L.append(list(x))
a = 0
b = 0
for i in range(math.factorial(N)):
    if L[i] == P:
        a = i
    if L[i] == Q:
        b = i

print(abs(a-b))

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

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

Solution (Python):
import itertools

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

N = [str(x) for x in range(1, n+1)]
All = []
for y in itertools.permutations(N):
    moji = ''
    for z in y:
        moji += z
    All.append(moji)

All = sorted(All)
p = ''
q = ''
for x in P:
    p += str(x)
for x in Q:
    q += str(x)

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

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
P = tuple([int(i) for i in input().split()])
Q = tuple([int(i) for i in input().split()])
li = [0] * N
for i in range(N) :
    li[i] = i+1
import itertools
from itertools import permutations
c = list(itertools.permutations(li))
a = 0
b = 0
for i in range(len(c)) :
    if c[i] == P :
        a = i
    if c[i] == Q :
        b = i
print(abs(b-a))

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

M = sorted(list(permutations(L, N)))

len_m = len(M)

a = -1
b = -1

for i in range(len_m):
  pSame = True
  qSame = True
  for j in range(N):
    if M[i][j] != P[j]:
      pSame = False
    if M[i][j] != Q[j]:
      qSame = False
  
  if pSame:
    a = i
  if qSame:
    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()))

a, b = 0, 0
perms = sorted(permutations(list(range(1, n+1))))
for i, perm in enumerate(perms):
  if p == perm:
    a = i+1
  if q == perm:
    b = i+1
print(abs(a-b))

Solution (Python):
import itertools

N = int(input())
P = ''.join([x for x in input().split()])
Q = ''.join([x for x in input().split()])
D = {}
for i, s in enumerate(sorted(itertools.permutations((str(n) for n in range(1, N + 1))))):
  D[''.join(s)] = i
print(abs(D[P] - D[Q]))

Solution (Python):

from __future__ import division, print_function

import os
import sys
import itertools
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


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

    f = -1
    s = -1

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

    print(abs(f - s))




BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")



if __name__ == "__main__":
    main()

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

sys.setrecursionlimit(10**9)
mod = 998244353
inf = 10**20

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()

n = I()
p = LI()
q = LI()

if p==q:
    print(0)
    exit()

l = [i for i in range(1,n+1)]
a=0
b=0
for i,x in enumerate(itertools.permutations(l)):
    if p==list(x):
        a = i
    if q==list(x):
        b = i
print(abs(a-b))

Solution (Python):
import itertools

n=int(input())
p=[int(x) for x in input().split()]
q=[int(x) for x in input().split()]

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



a=buf.index(tuple(p))+1
b=buf.index(tuple(q))+1

print(abs(a-b))

Solution (Python):
n=int(input())
P=[int(i) for i in input().split()]
Q=[int(i) for i in input().split()]
F=[1]
for i in range(8):
  F.append(F[-1]*(i+1))

a=1
b=1
def num(A,x):
  for i in range(len(A)):
    if A[i]==x:
      return i
N=[int(i) for i in range(1,n+1)]
M=[int(i) for i in range(1,n+1)]
for i in range(n):
  a+=num(N,P[i])*F[n-i-1]
  b+=num(M,Q[i])*F[n-i-1]
  N.remove(P[i])
  M.remove(Q[i])
print(abs(a-b))

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n=I()
  p=LI()
  q=LI()

  a=[i+1 for i in range(n)]
  ansa=0
  ansb=0
  for j,x in enumerate(itertools.permutations(a)):
    f1=True
    f2=True
    for i in range(n):
      if x[i]!=p[i]:
        f1=False
      if x[i]!=q[i]:
        f2=False
    if f1:
      ansa=j+1
    if f2:
      ansb=j+1

  
  return abs(ansa-ansb)


print(main())

Solution (Python):
import math
import bisect
import collections
import itertools
import heapq
import string
import sys
sys.setrecursionlimit(10**9)
def gcd(a,b):return math.gcd 
def lcm(a,b):return (a*b) // math.gcd(a,b) 
def iin(): return int(input()) 
def isn(): return input().split() 
def imn(): return map(int, input().split()) 
def iln(): return list(map(int, input().split())) 
def iln_s(): return sorted(iln()) 
def iln_r(): return sorted(iln(), reverse=True) 
def join(l, s=''): return s.join(l) 
def perm(l, n): return itertools.permutations(l, n) 
def perm_count(n, r): return math.factorial(n) // math.factorial(n-r) 
def comb(l, n): return itertools.combinations(l, n) 
def comb_count(n, r): return math.factorial(n) // (math.factorial(n-r) * math.factorial(r)) 
def divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i: divisors.append(n//i)
    return divisors
def is_prime(n):
    if n == 1: return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0: return False 
    return True
def primes(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n + 1, i): is_prime[j] = False
    return [i for i in range(n+1) if is_prime[i]]
def sieve_of_e(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n+1, i): is_prime[j] = False
    return is_prime

N = iin()
P = iln()
Q = iln()

PS = sorted(list(perm(P,N)))

p = 0
q = 0
for i in range(len(PS)):
    if P == list(PS[i]):
        p = i
    if Q == list(PS[i]):
        q = i
print(abs(p-q))

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

from itertools import permutations

sort_P = list(permutations(sorted(P)))

answer = 0
for i,x in enumerate(sort_P):
    if list(x) == P:
        answer += i + 1
    if list(x) == Q:
        answer -= i + 1

print(abs(answer))

Solution (Python):

import itertools

N = int(input())
P = tuple(map(int, input().split(' ')))
Q = tuple(map(int, input().split(' ')))
pnum = 0
qnum = 0

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

for idx, el in enumerate(itertools.permutations(l, N)):
    if el == P:
        pnum = idx + 1
    if el == Q:
        qnum = idx + 1
    if pnum != 0 and qnum != 0:
        break

print(abs(pnum-qnum))

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

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

Solution (Python):
import itertools


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

R = sorted(P)

for index, S in enumerate(list(itertools.permutations(R))):
    PS = sum([P[n] != S[n] for n in range(N)])
    QS = sum([Q[n] != S[n] for n in range(N)])
    if PS == 0:
        index_P = index
    if QS == 0:
        index_Q = index

print(abs(index_P - index_Q))

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

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

    per = list(itertools.permutations(tuple(range(1,N+1))))
    
    i = 0
    a = 0
    b = 0
    for p in per:
        if p == P:
            a = i
        if p == Q:
            b = i
        i += 1
    
    print(abs(a-b))

if __name__ == '__main__':
    solve()

Solution (Python):
import itertools

n = int(input())


p = input()
q = input()

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


prm = list(itertools.permutations(l))


a = None
b = None
for i in range(len(prm)):
    s = ' '.join(str(c) for c in prm[i])
    if s == p:
        a = i+1
    if s == q:
        b = i + 1


print(abs(a-b))

Solution (Python):
def f(n):
    if n == 1:
        return 1
    return f(n - 1) * n


n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
l = list(range(1, n + 1))
a = 0
for i, x in enumerate(p[:-1]):
    a += l.index(x) * f(n - i - 1)
    l.remove(x)
b = 0
l = list(range(1, n + 1))
for i, x in enumerate(q[:-1]):
    b += l.index(x) * f(n - i - 1)
    l.remove(x)
print(abs(b - a))

Solution (Python):
from sys import stdin
import itertools


if __name__ == "__main__":
  N = int(stdin.readline())
  P = tuple([int(i) for i in stdin.readline().split()])
  Q = tuple([int(i) for i in stdin.readline().split()])
  

  for i, perm in enumerate(sorted(list(itertools.permutations(range(1, 1+N))))):
    
    if perm == P:
      indexP = i
    if perm == Q:
      indexQ = i

  print(abs(indexP-indexQ))

Solution (Python):
import itertools

n = int(input())
seq = [i for i in range(1,n+1)]
p = list(map(int, input().split()))
q = list(map(int, input().split()))
p = tuple(p)
q = tuple(q)
a = list(itertools.permutations(seq))
ans = [0,0]
for i in range(len(a)):
    if a[i]==p:
        ans[0] = i+1

    if a[i] ==q:
        ans[1] = i+1
print(abs(ans[0]-ans[1]))

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

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

p_list = list(itertools.permutations(all, N))


def check_eq(A, B):
    flag = True
    for i in range(len(A)):
        if A[i] == B[i]:
            pass
        else:
            flag = False
            break
    return flag

a_num = 0
b_num = 0
for i in range(len(p_list)):
    if check_eq(p_list[i], A):
        a_num = i + 1
    if check_eq(p_list[i], B):
        b_num = i + 1
print(abs(a_num - b_num))

Solution (Python):
import itertools
n = int(input())
p = ''.join(input().split())
q = ''.join(input().split())
ans = 0
for i, a in enumerate(itertools.permutations('12345678' [:n], n)):
    s = ''.join(a)
    if p == s:
        ans += i
    if q == s:
        ans -= i
print(abs(ans))

Solution (Python):
N=int(input())
P=list(map(int,input().split()))
ps=""
for i in range(N):
  ps+=str(P[i])
Q=list(map(int,input().split()))
qs=""
for i in range(N):
  qs+=str(Q[i])

stack=[]
stack.append("")
res=[]
while stack:
  d=stack.pop()
  if len(d)==N:
    res.append(d)
    continue
  for i in range(1,N+1):
    if str(i) not in d:
      stack.append(d+str(i))
  
res=res[::-1]
a=0
b=0
for i in range(len(res)):
  if res[i]==ps:
    a=i+1
  if res[i]==qs:
    b=i+1

print(abs(a-b))

Solution (Python):
import itertools

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

a = 0
for _ in itertools.permutations(range(N)):
    if not(_ > Q) and not(_ < Q):
        break
    a += 1

b = 0
for _ in itertools.permutations(range(N)):
    if not(_ > P) and not(_ < P):
        break
    b += 1

print(abs(a-b))

Solution (Python):
import itertools

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

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

per = list(itertools.permutations(nums,r = N))

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

Solution (Python):
n=int(input())
a=[]
for i in range(1,n+1):
    a.append(i)
p=list(map(int,input().split()))
q=list(map(int,input().split()))
from itertools import permutations
perm=permutations(a)
aa=0
bb=0
count=0
for i in perm:
    f=True
    for j in range(n):
        if(i[j]!=p[j]):
            f=False
    if(f):
        aa=count
    f=True
    for j in range(n):
        if(i[j]!=q[j]):
            f=False
    if(f):
        bb=count
    if(aa and bb):
        break
    count+=1
    
print(abs(aa-bb))

Solution (Python):
import itertools

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

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

a = 0
b = 0
for v in itertools.permutations(li, N):
    a += 1
    b += 1
    aaa = 1
    bbb = 1
    for i in range(N):
        if v[i] != P[i]:
            aaa = 0
            break
    if aaa == 1:
        ansa = a
    for i in range(N):
        if v[i] != Q[i]:
            bbb = 0
            break
    if bbb == 1:
        ansb = b
print(abs(ansa-ansb))

Solution (Python):
from itertools import permutations
from sys import stdin


def main():
    input = lambda: stdin.readline()[:-1]
    N = int(input())
    P = tuple(map(int, input().split()))
    Q = tuple(map(int, input().split()))

    per = tuple(permutations(range(1, N + 1)))
    a = per.index(P)
    b = per.index(Q)
    print(abs(b - a))


main()

Solution (Python):
import itertools

N = int(input())

Ps = tuple(map(int, input().split()))
Qs = tuple(map(int, input().split()))

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

p_found = False
q_found = False
for i, p in enumerate(perms):
    if Ps == p:
        a = i
        p_found = True
    if Qs == p:
        b = i
        q_found = True
    if p_found and q_found:
        break

print(abs(a - b))

Solution (Python):
import bisect
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.append(i)
B = list(itertools.permutations(A))
C = []
for b in B:
  d = 0
  for bb in b:
    d *= 10
    d += bb
  C.append(d)
C.sort()

p = 0
for pp in P:
  p *= 10
  p += pp
q = 0
for qq in Q:
  q *= 10
  q += qq
a = bisect.bisect_left(C,p)
b = bisect.bisect_left(C,q)
print(abs(a-b))

Solution (Python):
N = int(input())
Ps = int("".join(input().split()))
Qs = int("".join(input().split()))

import itertools

l = list(range(1, N + 1))
l = itertools.permutations(l)
ln = []
for L in l:
    ln.append(int("".join(map(str, L))))
a = 0
b = 0
for i in range(len(ln)):
    if Ps == ln[i]:
        a = i
        break
for j in range(len(ln)):
    if Qs == ln[j]:
        b = j
        break

print(abs(a - b))

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

Q_list=list(itertools.permutations(sorted(Q)))
for i,q in enumerate(Q_list):
  q=list(q)
  if q==P:
    a=i
  if q==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()))
p = q = 0
for i,v in enumerate(permutations([i+1 for i in range(N)],N)):
    if P == v:
        p = i
    if Q == v:
        q = i
print(abs(q - p))

Solution (Python):
from itertools import permutations

n = int(input())
p = tuple(int(v) for v in input().split())
q = tuple(int(v) for v in input().split())

def fact(n):
    return fact(n - 1) * n if n > 1 else 1

ap = dict(zip(permutations(range(1, n + 1), n), range(fact(n))))
print(abs(ap[p] - ap[q]))

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

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


a = 0
b = 0
for i,s in enumerate(l):
    if P == s:
        a = i
    if Q == s:
        b = i
print(abs(a-b))

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

l = list(range(1, N + 1))
lst = []

for v in itertools.permutations(l, N):
	lst.append(v)
	
print(abs(lst.index(Q) - lst.index(P)))