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 fractions import gcd
from itertools import combinations,permutations,accumulate, product 

from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect














import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7


from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
  return int(readline())
n = I()
lis = list(range(1,n+1))
a,b = None,None
P = readInts()
Q = readInts()
i = 0
for A in permutations(lis,n):
    if list(A) == P == Q:
        a,b = i,i
    elif list(A) == Q:
        b = i
    elif list(A) == P:
        a = 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()))
R = [i+1 for i in range(N)]
RPS = sorted(list(itertools.permutations(R)))
print(abs(RPS.index(P)-RPS.index(Q)))

Solution (Python):
import itertools


def LI():
    return tuple(map(int, input().split()))


N = int(input())
P = LI()
Q = LI()
Nlist = list(range(1, N+1))
count = 1
for v in itertools.permutations(Nlist, N):
    if P == v:
        p = count
    if Q == v:
        q = count
    count += 1
print(abs(p-q))

Solution (Python):
from itertools import permutations
N = int(input())
P = tuple(list(map(int,input().split())))
Q = tuple(list(map(int,input().split())))
cnt = 0
for x in permutations(range(1,N+1),N):
    if P==x:
        indP = cnt
    if Q==x:
        indQ = cnt
    cnt += 1
print(abs(indP-indQ))

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

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


import itertools
X = []
for p in itertools.permutations(range(1, n+1)):
    X.append(p)

for i in range(len(X)):
    if P == X[i]:
        a = i
        break
for i in range(len(X)):
    if Q == X[i]:
        b = i
        break
print(abs(a-b))

Solution (Python):
import itertools
N = int(input())
lis = list(itertools.permutations(range(1, N+1)))
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
P = tuple(P)
Q = tuple(Q)
a = lis.index(P) + 1
b = lis.index(Q) + 1
ans = abs(a - b)
print(ans)

Solution (Python):
import math
n = int(input())
pli = list(map(int,input().split()))
qli = list(map(int,input().split()))
a,b = 0,0
for i in range(n-1):
    a += (pli[i]-1)*(math.factorial(n-1-i))
    for j in range(n-1-i):
        if pli[j+i+1] > pli[i]:
            pli[j+i+1] -= 1
for i in range(n-1):
    b += (qli[i]-1)*(math.factorial(n-1-i))
    for j in range(n-1-i):
        if qli[j+i+1] > qli[i]:
            qli[j+i+1] -= 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()))

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

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

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

n = int(stdin.readline().strip())
rank = dict([(val, i) for i, val in enumerate(sorted([int(''.join([str(v) for v in l])) for l in permutations(list(range(1, n+1)), n)])[::-1])])
p_rank = rank[int(''.join(stdin.readline().split()))]
q_rank = rank[int(''.join(stdin.readline().split()))]

print(abs(p_rank - q_rank))

Solution (Python):
import itertools
n = int(input())
p = input().replace(' ', '')
q = input().replace(' ', '')
s = itertools.permutations(list(range(1, n+1)), n)
pi = 0
qi = 0
for i, sb in enumerate(s):
    sb = ''.join(map(str, sb))
    if sb == p:
        pi = i
    if sb == q:
        qi = i

print(abs(pi-qi))

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

pcnt = 0
qcnt = 0
cnt=1

for l in itertools.permutations(range(1,n+1)):
    if p == l:
        pcnt = cnt
        break
    else:
        cnt += 1

cnt=1
for l in itertools.permutations(range(1,n+1)):
    if q == l:
        qcnt = cnt
        break
    else:
        cnt += 1
        
    

print(abs(qcnt-pcnt))

Solution (Python):
import itertools

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

patterns = itertools.permutations(list(range(1, N+1)), N)
p_i = 0
q_i = 0
for i, ptn in enumerate(patterns):
  p_same = True
  q_same = True
  for j, num in enumerate(ptn):
    if P[j] != num:
      p_same = False
    if Q[j] != num:
      q_same = False
  if p_same:
    p_i = i
  if q_same:
    q_i = i
print(abs(p_i-q_i))

Solution (Python):

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

def rec(l,s):
    if len(l)==N:
        L.append(l)
    else:
        for x in s:
            tmp_l = l[:]
            tmp_l.append(x)
            tmp_s = s[:]
            tmp_s.remove(x)
            rec(tmp_l,tmp_s)

rec(list(),[i+1 for i in range(N)])

a = 0
while P!=L[a]:
    a += 1
b = 0
while Q!=L[b]:
    b += 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()))

t = 0
x = 0
y = 0
for i in permutations(range(1,n+1), n):
  t += 1
  if i == p: x = t
  if i == q: y = t
print(abs(x-y))

Solution (Python):
import itertools

n = int(input())


per_list = []
for i in itertools.permutations([x for x in range(1, n + 1)]) :
    per_list.append(i)


a = []
for j in range(2) :
    y = tuple(map(int, input().split()))
    a.append(per_list.index(y))

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

Solution (Python):
from math import factorial
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
a=0
b=0
for i in range(n-1):
  A=0
  B=0
  for j in range(i+1,n):
    if p[i]>p[j]:
      A+=1
    if q[i]>q[j]:
      B+=1
  a+=factorial(n-i-1)*A
  b+=factorial(n-i-1)*B
  
print(abs(a-b))

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

s = itertools.permutations(range(1, n+1))
l = []
for v in s:
    l.append(v)
p_index = l.index(p)
q_index = l.index(q)
print(abs(p_index - q_index))

Solution (Python):
import math
import copy


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

    p_order = 1
    q_order = 1

    p_diff = []
    q_diff = []
    p_sort = list(range(1, 9))
    q_sort = list(range(1, 9))

    for i in range(n):
        
        p_diff.append(p_sort.index(p[i]))
        q_diff.append(q_sort.index(q[i]))
        p_sort.remove(p[i])
        q_sort.remove(q[i])

    for i in range(n):
        rest_p = len(p_diff[i+1:]) if i < n else 0
        rest_q = len(q_diff[i+1:]) if i < n else 0
        p_order += p_diff[i] * math.factorial(rest_p)
        q_order += q_diff[i] * math.factorial(rest_q)

    answer = abs(p_order - q_order)
    print(answer)


'''
    while p != []:
        i = 0
        diff = p[i] - min(p)
        if diff > 2:
            p_order += math.factorial(len(p) - 1)
        p.pop(i)
'''

'''
    pq_diff = [p[i] - q[i] for i in range(n)]

    answer = 0
    for i in range(n):
        if pq_diff[i] == 0:
            continue
        answer += (pq_diff[i] - 1) * math.factorial(n-i-1)
    print(answer
'''


if __name__ == "__main__":
    main()

Solution (Python):
import itertools as it
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
a = 0
b = 0
array = list(it.permutations(i for i in range(1,N+1)))
for i,ar in enumerate(array):
    if ar == P:
        a = i
    if ar == Q:
        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()))
a = 0
b = 0
now = 0
ls = [i+1 for i in range(N)]
for i in itertools.permutations(ls,N):
  now += 1
  if list(i) == P:
    a = now
  if list(i) == Q:
    b = now
print(abs(a-b))

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

l=[i for i in range(1,N+1)]
li=[]
for v in itertools.permutations(l,N):
    li.append(list(v))
a=li.index(list(map(int,input().split())))
b=li.index(list(map(int,input().split())))

print(abs(b-a))

Solution (Python):
import itertools
n = int(input())
R = [i for i in range(1,n+1)]
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))

i = 1
for r in itertools.permutations(R,n):
    if r == P:
        p = i
    if r == Q:
        q = i
    i += 1

print(abs(p-q))

Solution (Python):



import itertools
n=int(input())
l = [i for i in range(1,n+1)]
a=list(map(int,input().split()))
b=list(map(int,input().split()))
cnt=1
ans_a=0
ans_b=0
for v in itertools.permutations(l):
    if list(v)==a:
        ans_a=cnt
    if list(v)==b:
        ans_b=cnt        
    if ans_a!=0 and ans_b!=0:
        break
    cnt+=1
print(abs(ans_a-ans_b))

Solution (Python):
def func(x, y):
  if len(y)==1:
    dic.append(x*10+int(y))
  else:
    for j in range(len(y)):
      func(x*10+int(y[j]), y[:j]+y[j+1:])
dic = []
 
N = int(input())
func(0, "".join([str(i) for i in range(1,N+1)]))
 
A = int(input().replace(" ", ""))
B = int(input().replace(" ", ""))
ans = abs(dic.index(A)-dic.index(B))
print(ans)

Solution (Python):
from itertools import permutations as p

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

j = 0

for i in p(range(1, N + 1)):
  j += 1
  if i == P: a = j
  if i == Q: b = j

if a - b >= 0: print(a - b)
else: print(b - a)

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)]
permutations_l = list(itertools.permutations(l))

a, b = 0, 0
for i, R in enumerate(permutations_l):
  if R == P: a = i
for i, R in enumerate(permutations_l):
  if R == Q: b = i

print(abs(a-b))

Solution (Python):
import sys
import itertools


def resolve(in_):
    N = int(next(in_))
    P = tuple(map(int, next(in_).split()))
    Q = tuple(map(int, next(in_).split()))

    p = 0
    q = 0
    for i, R in enumerate(itertools.permutations(range(1, N + 1), N), 1):
        if not p and P == R:
            p = i
            if q:
                break
        if not q and Q == R:
            q = i
            if p:
                break
    
    answer = abs(p - q)

    return answer


def main():
    answer = resolve(sys.stdin)
    print(answer)


if __name__ == '__main__':
    main()

Solution (Python):
def abc150c_count_order():
    import bisect, itertools
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    pattern = list(itertools.permutations(range(1, n+1)))
    p_idx = bisect.bisect(pattern, p)
    q_idx = bisect.bisect(pattern, q)
    print(abs(p_idx-q_idx))
abc150c_count_order()

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

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

def pq(n,q):
    a = len(q) - 1
    if a == 0:
        n += q[0]
        return n
    else:
        plus = q.pop(0)
        return pq(n+plus*10**a, q)


def nBinarius(a, q):
    n = len(q) - 1
    if n == 0:
        b.append(a + q[0])
    else:
        j = 0
        for i in q:
            q.remove(i)
            nBinarius(a + i*(10**n), q)
            q.insert(j, i)
            j += 1
    return


p = pq(0, P)
q = pq(0, Q)
nBinarius(0, queue)
pn = 0
qn = 0
n = 0
for i in b:
    if p == i:
        pn = n
    if q == i:
        qn = n
    n += 1
        
print(abs(pn-qn))

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

Solution (Python):
import itertools

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

perm = list(itertools.permutations(range(1,N+1)))
for i in range(len(perm)):
    if P == perm[i]:
        a = i
    if Q == perm[i]:
        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()))
seq=[]
for i in range(N):
    seq.append(i+1)
l=list(itertools.permutations(seq))
print(abs(l.index(P)-l.index(Q)))

Solution (Python):
import itertools

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

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

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

Solution (Python):

import sys
import itertools
def input():
    return sys.stdin.readline()[:-1]

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

    l = [i + 1 for i in range(N)]
    p = itertools.permutations(l, N)
    q = itertools.permutations(l, N)
    c = 1
    d = 1
    a = 0
    b = 0
    for i in p:
        x = 0
        for j in range(N):
            if i[j] == P[j]:
                x += 1
            else:
                break
        if x == N:
            a = c
            break
        c += 1
    for i in q:
        x = 0
        for j in range(N):
            if i[j] == Q[j]:
                x += 1
            else:
                break
        if x == N:
            b = d
            break
        d += 1
    ans = abs(a - b)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import itertools
n=int(input())
P=tuple((map(int,input().split())))
Q=tuple((map(int,input().split())))
L=[]

for i in range(n):
    L.append(i+1)
    
M=list(itertools.permutations(L))


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

Solution (Python):
import itertools

N = int(input())

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

cntP = 0
cntQ = 0

for i in itertools.permutations(range(1,N+1)):
    if i == P:
        break
    cntP += 1

for i in itertools.permutations(range(1,N+1)):
    if i == Q:
        break
    cntQ += 1

print(abs(cntP - cntQ))

Solution (Python):
import itertools
n=int(input())
P=tuple((map(int,input().split())))
Q=tuple((map(int,input().split())))
L=[]

for i in range(n):
    L.append(i+1)
    
M=list(itertools.permutations(L))


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

Solution (Python):
import itertools
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
l = []
for i in range(1,N+1):
    l.append(i)
tmp = sorted(list(itertools.permutations(l)))

p = tmp.index(P)
q = tmp.index(Q)
print(abs(p-q))

Solution (Python):
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from itertools import permutations

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

    d = {x: i for i, x in enumerate(permutations(range(1, N + 1)))}

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


if __name__ == '__main__':
    main()

Solution (Python):
import itertools   

import math        






n = int(input())
p = list(input().split())
q = list(input().split())
nlis = sorted(p)

cntp = 0
cntq = 0

for idx, i in enumerate(itertools.permutations(nlis,n)):
    if list(i)==p:
        cntp = idx
    if list(i)==q:
        cntq = idx

print(abs(cntp-cntq))

Solution (Python):
count = 0


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


ans = []

def dfs(curr, p, q, n):
    if len(curr) == n:
        global count
        count+=1
        if curr == p:
            ans.append(count)
        if curr == q:
            ans.append(count)

        return 

    for i in range(1, n+1):
        if str(i) not in curr:
            dfs(curr + str(i), p, q, n)

for i in range(1, N + 1):
    dfs(str(i), P, Q, N)

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

Solution (Python):

def main():
    from itertools import permutations

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

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


if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
fact = [1]
for i in range(0,N):
  fact.append(fact[i] * (i+2))
p = 0
q = 0

def number(a):
  res = 0
  global fact
  l = len(a)
  for i in range(l-2):
    res += (a[i] - 1) * fact[l-2-i]
    for j in range(i+1, l-2):
      if a[j] > a[i]:
        a[j] -= 1
  if a[l-1] < a[l-2]:
    res += 2
  else:
    res += 1
  return res
    
p, q = number(P), number(Q)
print(abs(q-p))

Solution (Python):
import itertools

N = int(input())
P = list(map(int, input().split()))
tuple_P = tuple(P)
sorted_P = sorted(P)
Q = list(map(int, input().split()))
tuple_Q = tuple(Q)
sorted_Q = sorted(Q)

count_P = 1
for perm_P in itertools.permutations(sorted_P):
    if tuple_P == perm_P:
        break
    count_P += 1

count_Q = 1
for perm_Q in itertools.permutations(sorted_Q):
    if tuple_Q == perm_Q:
        break
    count_Q += 1

answer = abs(count_P - count_Q)
print(answer)

Solution (Python):
from itertools import permutations

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

l = sorted(permutations(range(1, N + 1), N))
d = {''.join(map(str, k)): v+1 for v, k in enumerate(l)}
print(abs(d[P]-d[Q]))

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

perm = []
for num in itertools.permutations(list(range(1,N+1)),N):
    num = [str(n) for n in num]
    num = int(''.join(num))
    perm.append(num)
perm.sort()
p_ind = perm.index(P)
q_ind = perm.index(Q)

print(abs(p_ind-q_ind))

Solution (Python):
import itertools

def main():
    number = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    num_list = list(range(1, number+1))
    permu = list(itertools.permutations(num_list, number))
    where_p = permu.index(p)
    where_q = permu.index(q)
    print(abs(where_p-where_q))
if __name__ == '__main__':
    main()

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

Solution (Python):

from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def ceil(a, b):
    return (a + b - 1) // b


def sum_of_arithmetic_progression(s, d, n):
    return n * (2 * s + (n - 1) * d) // 2


def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


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



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

    p = 0
    q = 0
    for i, v in enumerate(permutations(range(1, N + 1)), start=1):
        p_ok = True
        q_ok = True
        for j in range(N):
            p_ok &= v[j] == P[j]
            q_ok &= v[j] == Q[j]

        if p_ok:
            p = i
        if q_ok:
            q = i

    print(abs(p - q))


def main():
    solve()


if __name__ == '__main__':
    main()

Solution (Python):
import itertools

n=[x for x in range(1,int(input())+1)]
P=list(map(int, input().split()))
Q=list(map(int, input().split()))

for i, a in enumerate(itertools.permutations(n), start=1):
  if list(a)==P:
    p=i
  if list(a)==Q:
    q=i
print(abs(p-q))

Solution (Python):
import itertools
import math

N = int(input())
M = math.factorial(N)
X = [i for i in range(1, N + 1)]
Y = list(itertools.permutations(X))

P = tuple([int(x) for x in input().split()])
Q = tuple([int(x) for x in input().split()])
for i in range(M):
    if Y[i] == P:
        a = i
    if Y[i] == Q:
        b = i

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

Solution (Python):
import math
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
a, b = 0, 0
A, B = set(), set()
for i in range(N):
    n = N - i - 1
    m = P[i] - i - 1
    for ai in A:
        if ai < P[i]:
            m -= 1
    a += m * math.factorial(n)
    A.add(P[i])
for i in range(N):
    n = N - i - 1
    m = Q[i] - i - 1
    for bi in B:
        if bi < Q[i]:
            m -= 1
    b += m * math.factorial(n)
    B.add(Q[i])
print(abs(a - b))

Solution (Python):
import sys
from collections import deque

import math

def S(): return sys.stdin.readline().rstrip()
def SL(): return map(str,sys.stdin.readline().rstrip().split())
def I(): return int(sys.stdin.readline().rstrip())
def IL(): return map(int,sys.stdin.readline().rstrip().split())

def order(l):
    flag = [True]*n
    ret = 0
    for i,item in enumerate(l):
        count = 0
        for j in range(n):
            if item-1==j:
                flag[j] = False
                break
            if not flag[j]:
                continue
            count += 1
        ret += fact[n-i-1]*count
    ret += 1
    return ret

def solve():
    a = order(p)
    b = order(q)
    print(abs(a-b))
    return

if __name__=='__main__':
    fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320]
    n = I()
    p = list(IL())
    q = list(IL())
    solve()

Solution (Python):
import itertools

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

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

ans = 0
cnt = 0
for i in range(len(pat)):
    if pat[i]==p or pat[i]==q:
        if p==q:
            print(0)
            break
        if cnt==1:
            print(i-ans)
            break
        ans = i
        cnt = 1

Solution (Python):
import sys
sys.setrecursionlimit(10**7) 
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right

from collections import deque, defaultdict


from collections import Counter

from itertools import accumulate,combinations,permutations,product

from heapq import heapify,heappop,heappush

from functools import reduce,lru_cache

from decimal import Decimal
from argparse import ArgumentParser

args=ArgumentParser()
args.add_argument('-loc', '--local', type=bool,default=False)
LOCAL=args.parse_args().local

def input(): 
    x=sys.stdin.readline(); 
    if x[-1]=="\n": 
        return x.rstrip() 
    return x
    
def printe(*x):_=print("
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): 
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

def main():
    mod = 1000000007
    

    N = int(input())
    
    P = tuple(map(int, input().split())) 
    Q = tuple(map(int, input().split()))
    
    
    a=-1
    b=-1
    cnt=0
    for j in permutations(tuple(range(1,N+1)),N):
        cnt+=1
        jt=tuple(j)
        if jt==P:
            a=cnt
        if jt==Q:
            b=cnt
    print(abs(a-b))




if __name__ == "__main__":
    main()

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

import itertools

if P == Q:
    print(0)
else:
    perm = [i for i in range(1, N+1)]

    count = 0
    numlst = []
    for v in itertools.permutations(perm, N):
        count += 1
        if tuple(P) == v or tuple(Q) == v:
            numlst.append(count)

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

Solution (Python):
import itertools


def abc150c_count_order():
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    pattern = list(itertools.permutations(range(1, n + 1), n))
    print(abs(pattern.index(p)-pattern.index(q)))


abc150c_count_order()

Solution (Python):
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
import math
def num(P):
    l = list(range(N+1))
    l.remove(0)
    p = 1
    for i in range(N):
        p += l.index(P[i]) * math.factorial(N-1-i)
        l.remove(P[i])
    return p
ans = num(P) - num(Q)
print(abs(ans))

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

c_p = 0
c_q = 0
count = 0
for i in itertools.permutations(sorted(p),len(p)):

    if p == list(i):
        c_p = count
    if q == list(i):
        c_q = count
    count += 1

print(abs(c_p - c_q))

Solution (Python):
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
cnt1=0
cnt2=0
j=1
import itertools
for i in itertools.permutations(range(1,n+1)):
    if list (i)==p:
        a=j
    if list(i)==q:
        b=j
    j+=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))))
print(abs(lst.index(p) - lst.index(q)))

Solution (Python):
import itertools

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

a = 0
b = 0
j = 0
for i in itertools.permutations([int(x+1) for x in range(N)]):
    j += 1
    if(list(i) == P) :
        a = j
    if(list(i) == Q) :
        b = j

print(abs(a-b))

Solution (Python):
n=int(input())
a=tuple(map(int, input().split()))
b=tuple(map(int, input().split()))
cnta=0
cntb=0
li=[i for i in range(1,n+1)]
import itertools
k=0
for i in itertools.permutations(li):
    if tuple(i)==a:
        cnta=k
    if tuple(i)==b:
        cntb=k
    k+=1
print(abs(cnta-cntb))

Solution (Python):
n=int(input())
a=list(map(int, input().split()))
b=list(map(int, input().split()))
cnta=0
cntb=0
li=[i for i in range(1,n+1)]
import itertools
k=0
for i in itertools.permutations(li):
    if list(i)==a:
        cnta=k
    if list(i)==b:
        cntb=k
    k+=1
print(abs(cnta-cntb))

Solution (Python):
import itertools

n = int(input())
a = [i for i in range(1,n+1)]
b = list(itertools.permutations(a))
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
pi = b.index(p)
qi = b.index(q)

print(abs(pi - qi))

Solution (Python):
import sys, bisect, math, itertools, string, queue, copy
import numpy as np
import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush

sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return tuple(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplt(n): return [tuple(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

n = inp()
P = inpl()
Q = inpl()

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

per=itertools.permutations(range(1, n+1), n)
for i, v in enumerate(per):
    if(p==v): pi=i
    if(q==v): qi=i

print(abs(pi-qi))

Solution (Python):


import itertools


def get_input() -> tuple:
    """
    標準入力を取得する.

    Returns:\n
        tuple: 標準入力
    """
    
    N = int(input())
    P = tuple(map(int, input().split()))
    Q = tuple(map(int, input().split()))

    return N, P, Q


def main(N: int, P: tuple, Q: tuple) -> None:
    """
    メイン処理.

    Args:\n
        N (int): 数列の大きさ
        P (tuple): 順列
        Q (tuple): 順列
    """
    
    p = 0
    q = 0
    order = 1
    for t in itertools.permutations(range(1, N + 1), N):
        if t == P:
            p = order
        if t == Q:
            q = order
        order += 1

    ans = abs(p - q)

    
    print(ans)


if __name__ == "__main__":
    
    N, P, Q = get_input()

    
    main(N, P, Q)

Solution (Python):


import itertools


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


p = 0
q = 0
order = 1
for t in itertools.permutations(range(1, N + 1), N):
    if t == P:
        p = order
    if t == Q:
        q = order
    order += 1

ans = abs(p - q)


print(ans)

Solution (Python):
import itertools
N=int(input())
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
ans=list(itertools.permutations(list(range(1,N+1))))
print(abs(ans.index(P)-ans.index(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(list(range(1, n+1))))
print(abs(l.index(p)-l.index(q)))

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

p = sorted(list(permutations(P)))
q = sorted(list(permutations(Q)))

print(abs(p.index(P) -  q.index(Q)))