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

Solution (Python):
from itertools import permutations

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

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

a = r.index(p) + 1
b = r.index(q) + 1

print(abs(a - b))

Solution (Python):
import itertools

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

base=list(itertools.permutations(P))
base.sort()


ans=abs(base.index(P)-base.index(Q))

print(ans)

Solution (Python):
from functools import reduce
from fractions import gcd
import math
import bisect
import itertools
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline
INF = float("inf")


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

    a = 0
    b = 0
    cnt = 0
    for R in itertools.permutations(range(1, N+1), N):
        R = [r for r in R]
        cnt += 1
        if R == P:
            a = cnt
        if R == Q:
            b = cnt
        
    
    print(abs(a-b))


if __name__ == '__main__':
    main()

Solution (Python):
from math import factorial
n = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
a = 0
b = 0

for i in range(n):
    a+= (p[i]-1)*factorial(n-1-i)
    b+= (q[i]-1)*factorial(n-1-i)
    for j in range(n):
        if p[i] < p[j]:
            p[j] -= 1
        if q[i] < q[j]:
            q[j] -= 1

print(abs(a-b))

Solution (Python):
from math import factorial
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
P1 = [1,2,3,4,5,6,7,8]
Q1 = [1,2,3,4,5,6,7,8]
Pcnt = 0
Qcnt = 0
for i in range(N-1):
  Pcnt += P1.index(P[i])*(factorial(N-1-i))
  P1.remove(P[i])
  Qcnt += Q1.index(Q[i])*(factorial(N-1-i))
  Q1.remove(Q[i])
print(abs(Pcnt-Qcnt))

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

Solution (Python):
import math
n = int(raw_input())
p = map(int,raw_input().split())
q = map(int,raw_input().split())
p_n = 0
q_n = 0
n_list = [i for i in range(1,n+1)]
f_list = [math.factorial(i) for i in range(n)]
f_list = f_list[::-1]
for a in range(n):
  p_n += n_list.index(p[a])*f_list[0]
  n_list.remove(p[a])
  f_list.pop(0)
  
n_list = [i for i in range(1,n+1)]
f_list = [math.factorial(i) for i in range(n)]
f_list = f_list[::-1]
for a in range(n):
  q_n += n_list.index(q[a])*f_list[0]
  n_list.remove(q[a])
  f_list.pop(0)

print abs(p_n - q_n)

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


import itertools

f=list(itertools.permutations(p))

newf=[]

for i in range(len(f)):
    ff=""
    for ii in range(n):
        ff+=f[i][ii]
    newf.append(ff)

newf=[int(i) for i in newf]
newf.sort()

pp=""
for i in p:
    pp+=i
p=int(pp)
qq=""
for i in q:
    qq+=i
q=int(qq)


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

Solution (Python):
import itertools
n = list(range(1, int(input())+1))
p, q = input(), input()
a = [str(x) for x in n]
new_list = []
for x in itertools.permutations(a):
    new_list.append(" ".join(x))
print(abs(new_list.index(p) - new_list.index(q)))

Solution (Python):
import itertools
n=int(input())
p=[int(i) for i in input().split()]
q=[int(i) for i in input().split()]
w=sorted(p)
p=tuple(p)
q=tuple(q)
ans=[0,0]
for a,i in enumerate(list(itertools.permutations(w))):
    if i==p:
        ans[0]=a
    if i==q:
        ans[1]=a
print(abs(ans[0]-ans[1]))

Solution (Python):
import itertools

N = input()
P = input()
Q = input()
PList = P.split()
QList = Q.split()

PQList = []
for i in itertools.permutations(range(1,int(N) + 1)):
    x = list(i)
    x_str = [str(n) for n in x]
    PQList.append(x_str)


a = PQList.index(PList) + 1
b = PQList.index(QList) + 1
print(abs(a - b))

Solution (Python):
import itertools as it

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

cnt = 0
for i in it.permutations([i for i in range(1, n + 1)], n):
    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 = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
a = b = 0
l = []

for i in range(1, n+1):
  l.append(i)

all_list = list(itertools.permutations(l))
a = all_list.index(p) + 1
b = all_list.index(q) + 1
print(abs(a - b))

Solution (Python):
kaijo = [1]
for i in range(1, 9):
  kaijo.append(kaijo[i-1]*i)

def numberof(n, p):
  rtn = 0
  order = list(range(1,n+1))
  for i, x in enumerate(p[:-1]):
    idx = order.index(x)
    order.pop(idx)
    rtn += kaijo[len(order)]*idx
  return rtn+1

N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
print(abs(numberof(N, Q)-numberof(N, P)))

Solution (Python):
import itertools
n = int(input())
sp = str(list(map(int,input().split())))
sq = str(list(map(int,input().split())))

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

p = list(itertools.permutations(d))


order_dict = {}
for i in range(len(p)):
    order_dict[str(p[i])] = i

sp_str = sp.replace('[', '(').replace(']',')')
sq_str = sq.replace('[', '(').replace(']',')')

print(abs(order_dict[sq_str] - order_dict[sp_str]))

Solution (Python):

 
import math
import itertools
import sys
import copy
 






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

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


pk = 0
qk = 0

for i in range(len(T)) :
  
  cntP = 0
  cntQ = 0
  for j in range(N) :
    if T[i][j] == P[j] :
      cntP += 1
    if T[i][j] == Q[j] :
      cntQ += 1
  
  if cntP == N :
    pk = i+1
  if cntQ == N :
    qk = i+1



print (abs(pk-qk))

Solution (Python):
import sys
import math
import itertools as it
def i():return int(sys.stdin.readline().replace("\n",""))
def i2():return map(int,sys.stdin.readline().replace("\n","").split())
def s():return str(sys.stdin.readline().replace("\n",""))
def l():return list(sys.stdin.readline().replace("\n",""))
def intl():return [int(k) for k in sys.stdin.readline().replace("\n","").split()]
def lx():return list(map(lambda x:int(x)*-1,sys.stdin.readline().replace("\n","").split()))
def t():return tuple(map(int,sys.stdin.readline().replace("\n","").split()))

if __name__ == "__main__":pass

n = i()
p = t()
q = t()
pt = 1
ck = 0
l = [i for i in range(1,n+1)]
for i in it.permutations(l):
    if p == i:
        cnt1 = pt
        ck += 1
    elif i == q:
        cnt2 = pt
        ck += 1
    pt += 1
if ck >= 2:
    print(abs(cnt1-cnt2))
else:
    print(0)

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

N = int(readline())

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

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


def a(b):
    s = sorted(b)
    c = 0
    for i in b:
        rank = s.index(i)
        c += pr(len(s) - 1) * rank
        s.remove(i)
    return c

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

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

Solution (Python):
import math


def cnt(l):
    n = 1
    while not l == []:
        x = l.pop(0)
        n += math.factorial(len(l)) * len([y for y in l if y < x])
    return n


def resolve():
    n = int(input())
    p = list(map(int, input().split()))
    q = list(map(int, input().split()))
    print(abs(cnt(p) - cnt(q)))


if __name__ == '__main__':
    resolve()

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

def calc(A):
    n = len(A)
    ans = 0
    for i in range(n):
        a = A[i]-1
        for x in A[:i]:
            if x<A[i]:
                a -= 1
        fr = 1
        for i in range(1,n-i):
            fr *= i
        ans += a * fr
    return ans


def main():
    N = I()
    P = LI()
    Q = LI()

    print(abs(calc(P)-calc(Q)))
    

if __name__ == "__main__":
    main()

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

p = list(itertools.permutations([i for i in range(1, N+1)], N))
print(abs(p.index(P) - p.index(Q)))

Solution (Python):
import itertools

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

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

list_data = []
for val in itertools.permutations(data):
    list_data.append(val)

list_data.sort()

a = 0
b = 0
i = 1
for val in list_data:
    if val == P:
        a = i
    if val == Q:
        b = i
    i += 1

if a >= b:
    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()))

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

data = [_ for _ in range(1, n+1)]

result = list(map(list, itertools.permutations(data, n)))


for i, row in enumerate(result):
    
    if row == p:
        a = i + 1
    if row == q:
        b = i + 1

    if a > 0 and  b > 0:
        break

print(abs(a - b))

Solution (Python):
import itertools

def j(a,b):
    for i in range(len(a)):
        if a[i]!=b[i]:
            return False
    return True
a=0
n=int(input())
p=int(input().replace(" ",""))
q=int(input().replace(" ",""))
k,l=0,0
for i in itertools.permutations("".join([str(i+1)for i in range(n)])):
    a+=1
    if j(i,str(p)):
        k=a
    if j(i,str(q)):
        l=a
print(abs(l-k))

Solution (Python):
import itertools
N=int(input())
S=[]
T=[]
P = list(map(int,input().split()))
p=''.join(map(str,P))
Q = list(map(int,input().split()))
q=''.join(map(str,Q))
for i in range(1,N+1):
  S.append(str(i))
for v in itertools.permutations(S, N):
    T.append(''.join(map(str,v)))


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

Solution (Python):
import itertools

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

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

list_data = []
for val in itertools.permutations(data):
    list_data.append(val)

list_data.sort()

a = 0
b = 0
i = 1
for val in list_data:
    if val == P:
        a = i
    if val == Q:
        b = i
    i += 1

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

Solution (Python):
import itertools
n=int(input())
li_a =  list(map(int,input().split()))
li_b =  list(map(int,input().split()))
li_f = list()
for i in range(n):
    li_f.append(i+1)
li_j = list(itertools.permutations(li_f, n))
print(abs(li_j.index(tuple(li_a))-li_j.index(tuple(li_b))))

Solution (Python):
import itertools

N = int(input())

myseq = [ n for n in range(1, N+1)]



mylsit =  list(itertools.permutations(myseq))

p = tuple(map(int, input().split()))
P = mylsit.index(p)
q = tuple(map(int, input().split()))
Q = mylsit.index(q)
print(abs(P-Q))

Solution (Python):
import itertools
import numpy as np

n = input()
p = input().split()
q = input().split()

tmp = []
for p1 in p:
    tmp.append(int(p1))
p = tuple(tmp)

tmp = []
for p1 in q:
    tmp.append(int(p1))
q = tuple(tmp)

aa = list(itertools.permutations(np.arange(1, int(n) + 1)))
id1 = aa.index(p)
id2 = aa.index(q)

print(abs(id1 - id2))

Solution (Python):
import math
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
a=0
b=0
c=sorted(p)
d=sorted(p)

for i in range(n):
    a+=(c.index(p[i]))*math.factorial(n-i-1)
    b+=(d.index(q[i]))*math.factorial(n-i-1)
    c.pop(c.index(p[i]))
    d.pop(d.index(q[i]))

print(int(math.fabs(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)))
ans=abs(l.index(p)-l.index(q))
print(ans)

Solution (Python):
import math

def bangou(array, n):
    nl = []
    for i in range(n):
        nl.append(i+1)

    num = 0
    while array:
        k = array.pop(0) 
        a = nl.index(k)      
        num += a * math.factorial(len(array))
        nl.remove(k)

    return num
        

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

v = bangou(p,n)
w = bangou(q,n)

print(abs(v-w))

Solution (Python):
import itertools

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

A = sorted(P)
count=0

for v in itertools.permutations(A, N):
    if P == list(v):
        p_cou = count
    if Q == list(v):
        q_cou = count
    count += 1

print(abs(q_cou-p_cou))

Solution (Python):
n = int(input())
pl = list(map(int,input().split()))
ql = list(map(int,input().split()))


import itertools
a = list(itertools.permutations(pl))
a = sorted([list(i) for i in a])

print(abs(a.index(pl) - a.index(ql)))

Solution (Python):
import itertools

n = int(input())
a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))
z = []
c = 0
d = 0

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

Lst = list(itertools.permutations(z))

for i in range(len(Lst)):
    if Lst[i] == a:
        c = i
    if Lst[i] == b:
        d = i

print(abs(c - d))

Solution (Python):
n = int(raw_input())
s1 = raw_input().split(" ")
s2 = raw_input().split(" ")
ss1 = []
for i in s1:
  ss1.append(int(i))
s1 = tuple(ss1)

ss2 = []
for i in s2:
  ss2.append(int(i))
s2 = tuple(ss2)

from itertools import permutations


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

t= 0
s1c = None
s2c = None
for i in list(perm):
    if s1 == i:
      s1c = t
    if s2 == i:
      s2c = t
    if s1c and s2c:
    	break
    t += 1
print(abs(s1c-s2c))

Solution (Python):
import itertools
n = int(input())
p = int(input().replace(" ", ""))
q = int(input().replace(" ", ""))
li = []
num = [i + 1 for i in range(n)]
for i in itertools.permutations(num, n):
    s = ""
    for c in i:
        s += str(c)
    li.append(int(s))
print(abs(li.index(p) - li.index(q)))

Solution (Python):
import itertools
n = int(input())
l = list(range(1,n+1))

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

p1 = list(itertools.permutations(l, n))
pcount = 0
qcount = 0

ans = abs(p1.index(p) - p1.index(q))
print(ans)

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())
l = list(itertools.permutations(range(1, n + 1)))
print(abs(l.index(p) - l.index(q)))

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


import itertools

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

pi = pat.index(P) + 1
qi = pat.index(Q) + 1

if pi - qi < 0:
    print(qi - pi)
else:
    print(pi - qi)

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

p_unused = list(range(1,N+1))
q_unused = list(range(1,N+1))

di_p = 0
di_q = 0
for i in range(N):
    p_num = p_unused.index(P[i])
    p_unused.remove(P[i])
    di_p += p_num * math.factorial(N-i-1)

    q_num = q_unused.index(Q[i])
    q_unused.remove(Q[i])
    di_q += q_num * math.factorial(N-i-1)

print(abs(di_p-di_q))

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

*per, = itertools.permutations(range(1, n+1))

a = bisect.bisect_right(per, p)
b = bisect.bisect_right(per, 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()))
a, b = [-1]*2
for i,p in enumerate(permutations(range(1,N+1))):
  if a>0 and b>0: break
  if p == P: a = i
  if p == Q: b = i
print(abs(a-b))

Solution (Python):
import itertools
import math

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

li = [0] * n
for i in range(n):
    li[i] = i + 1

sub = list(itertools.permutations(li, n))

pans = 0
qans = 0
so = math.factorial(n)
for i in range(so):
    for j in range(n):
        if sub[i][j] != p[j]:
            break
        if j == n - 1:
            pans = i + 1

for i in range(so):
    for j in range(n):
        if sub[i][j] != q[j]:
            break
        if j == n - 1:
            qans = i + 1

print(max(pans, qans) - min(pans, qans))

Solution (Python):
from math import factorial

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

pp = 0
qq = 0
pl = []
ql = []

for i in range(n):
    p_cnt = 0
    q_cnt = 0
    pn = p[i]
    qn = q[i]
    
    if i > 0:
        for j in range(len(pl)):
            if pn > pl[j]:
                p_cnt += 1
            if qn > ql[j]:
                q_cnt += 1

    pp+=(pn-p_cnt)*factorial(n-i-1)
    qq+=(qn-q_cnt)*factorial(n-i-1)

    pl.append(pn)
    ql.append(qn)
print(abs(pp-qq))

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

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

p_place = r.index(p)
q_place = r.index(q)
answer = abs(p_place-q_place)
print(answer)

Solution (Python):
import itertools

k =input()
arr1 = [int(i) for i in input().split()]
arr2 = [int(i) for i in input().split()]

newArr = list(itertools.permutations(sorted(arr1)))
print(abs(newArr.index(tuple(arr1)) - newArr.index(tuple(arr2))))

Solution (Python):
from itertools import permutations

n = int(input())
na = [i for i in range(1, n+1)]
nb = [i for i in range(1, n+1)]
x = [int(i) for i in input().strip().split(' ')]
y = [int(i) for i in input().strip().split(' ')]

a = list(permutations(na)).index(tuple(x))
b = list(permutations(nb)).index(tuple(y))

print(abs(a-b))

Solution (Python):
import math
n = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
def a(n, P):
  ret = 0
  for i in range(n):
    ret = ret + (P[i] - 1) * math.factorial(n-i-1)
    for j in range(i+1, n):
      if P[j] > P[i]:
        P[j] = P[j] - 1
  return ret
print(abs(a(n, P)-a(n, Q)))

Solution (Python):
import itertools

n = int(input())

p_list = [int(i) for i in input().split()]
q_list = [int(i) for i in input().split()]

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

a = 0
b = 0

for i, v in enumerate(itertools.permutations(num_list, n)): 
    if(list(v) == p_list):
        a = i
    if(list(v) == q_list):
        b = i
print(abs(a - b))

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

import itertools
import numpy as np

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

pp=""
for p in P:
    pp+=str(p)
qq=""
for q in Q:
    qq+=str(q)
for i in range(len(X)):
    y=""
    for x in X[i]:
        y+=str(x)
    if y==pp:
        a=len(X)-i
    if y==qq:
        b=len(X)-i
print(abs(a-b))

Solution (Python):

import itertools

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

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

per = itertools.permutations(lis, len(lis))

all = []
for v in per:
    all.append(v)

tp_p = tuple(p)
tp_q = tuple(q)

for i in range(len(all)):
    if tp_p == all[i]:
        a = i+1
    if tp_q == all[i]:
        b = i+1

print(abs(a-b))

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

Solution (Python):
N = int(input())
ps = tuple(map(int, input().split()))
qs = tuple(map(int, input().split()))
from itertools import permutations
for i, x in enumerate(permutations(range(1,N+1), N)):
    if x == ps:
        j = i
    if x == qs:
        t = i
print(abs(t-j))

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

def add(i, x):
    while i <= n:
        data[i] += x
        i += i & -i
def get(i):
    s = 0
    while i:
        s += data[i]
        i -= i & -i
    return s 

np = 1
data = [0]*(n+1)
fact = [1]*(n+1)
for i in range(1, n):
    fact[i] = (fact[i-1]*i)

for i, a in enumerate(p):
    v = a - get(a)
    add(a, 1)
    np += fact[n-i-1]*(v-1)

nq = 1
data = [0]*(n+1)
fact = [1]*(n+1)
for i in range(1, n):
    fact[i] = (fact[i-1]*i)

for i, a in enumerate(q):
    v = a - get(a)
    add(a, 1)
    nq += fact[n-i-1]*(v-1)

print(abs(np-nq))

Solution (Python):
import itertools

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

itc = list(itertools.permutations(sorted(p)))

a = b = 0
for i in range(len(itc)):
  if p == itc[i]:
    a = i
    break

for i in range(len(itc)):
  if q == itc[i]:
    b = i
    break

print(abs(a-b))

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

aaa = tuple(p)
bbb = tuple(q)
pm = list(itertools.permutations(set(p)))
a = pm.index(aaa) + 1
b = pm.index(bbb) + 1
print(abs(a-b))

Solution (Python):
from sys import stdin
from itertools import accumulate, dropwhile, takewhile, groupby
import bisect
import copy
import math
import itertools
N = int(stdin.readline().rstrip())
A = tuple(stdin.readline().rstrip().split())
B = tuple(stdin.readline().rstrip().split())
add = []
for el in range(N):
    add.append(str(el+1))
p = itertools.permutations(add, N)
data = []
for el in p:
    data.append(el)
a = data.index(A)
b = data.index(B)
print(abs(b-a))

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

Solution (Python):
def main():
    N = int(input())
    X = tuple(map(int, input().split()))
    Y = tuple(map(int, input().split()))

    if X == Y:
        print(0)
        return

    P = {v: i for i, v in enumerate(sorted(permutations(range(1, N + 1))))}
    print(abs(P[X] - P[Y]))


def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return


if __name__ == "__main__":
    main()

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

Solution (Python):
def p_c():
    from itertools import permutations
    N = int(input())
    st_list = "".join(map(str, range(1, N+1)))
    *P, = map(int, input().split())
    *Q, = map(int, input().split())
    *per, = permutations(range(1, N + 1))
    per.sort()
    li = []
    for p in per:
        li.append("".join(map(str, p)))
    p = "".join(map(str, P))
    q = "".join(map(str, Q))
    print(abs(li.index(q) - li.index(p)))
    
p_c()

Solution (Python):
import itertools

k =input()
arr1 = [int(i) for i in input().split()]
arr2 = [int(i) for i in input().split()]

newArr = list(itertools.permutations(sorted(arr1)))
print(abs(newArr.index(tuple(arr1)) - newArr.index(tuple(arr2))))

Solution (Python):
import itertools
N=int(input())
M=list(range(1,N+1))
P=[int(x) for x in input().split()]
Q=[int(x) for x in input().split()]
p=0
q=0
c=0
for Y in itertools.permutations(M):
  c +=1
  if list(Y)==P:
    p=c
  if list(Y)==Q:
    q=c
print(abs(p-q))

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

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

nnn = 1
for i in range(1, N+1):
    nnn *= i


aaa = nnn
a = 0
for i in range(N-1):
    x = P.pop(0)
    idx = m.index(x)
    m.pop(idx)
    aaa //= N-i
    a += idx*aaa

bbb = nnn
b = 0
for i in range(N-1):
    x = Q.pop(0)
    idx = l.index(x)
    l.pop(idx)
    bbb //= N-i
    b += idx*bbb
    

print(abs(a-b))

Solution (Python):
N = int(input())
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]
def get_order(N, src):
    MOD = 10**9+7

    bit = [0] * (N+1)
    def bit_add(a,w):
        x = a
        while x <= N:
            bit[x] += w
            x += (x & -x)

    def bit_sum(a):
        x = a
        ret = 0
        while x > 0:
            ret += bit[x]
            x -= (x & -x)
        return ret

    ans = fac = 1
    for i in range(N-1,-1,-1):
        a = src[i]
        ans += (bit_sum(a) * fac) % MOD
        bit_add(a,1)
        fac = (fac * (N-i)) % MOD

    return ans % MOD
print(abs(get_order(N,P)-get_order(N,Q)))

Solution (Python):
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations,groupby
import sys
import bisect
import string
import math
import time
import random
def S_():
    return input()
def LS():
    return [i for i in input().split()]
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def NI(n):
    return [int(input()) for i in range(n)]
def NI_(n):
    return [int(input())-1 for i in range(n)]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def LtoS(ls):
    return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)]
        rt+=[s]
    return rt
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()

input=lambda: sys.stdin.readline().rstrip()
import fractions
gcd=fractions.gcd
def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

ans=0

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

k=permutations(range(1,n+1))
for j,i in enumerate(k):
    if p==i:pn=j
    if q==i:qn=j
    


ans=abs(pn-qn)
print(ans)

Solution (Python):
from itertools import permutations

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

i = 0
a = 0
b = 0
for s in permutations(range(1, n+1)):
    for j in range(n):
        if p[j] != s[j]:
            break
    else:
        a = i
    for j in range(n):
        if q[j] != s[j]:
            break
    else:
        b = i
    i += 1

print(abs(a-b))

Solution (Python):


from sys import stdin

N = int(stdin.readline())
P = [int(wd) for wd in stdin.readline().split()]
Q = [int(wd) for wd in stdin.readline().split()]

def kaijou(n):
    if n == 1:
        return 1
    return n * kaijou(n-1)

def convert(R, R0):
    if len(R) == 1:
        return 0
    n = R0.index(R[0])
    nR = R[1:]
    nR0 = list(R0)
    del nR0[n]
    return n * kaijou(len(nR)) + convert(nR, nR0)

p = convert(P, list(range(1, N+1)))
q = convert(Q, list(range(1, N+1)))

print(abs(p - q))

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

Solution (Python):
import itertools

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

x=list(range(N+1))
del x[0]
li=list(itertools.permutations(x))

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

print(abs(a-b))

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

import itertools
plist = list(itertools.permutations([i+1 for i in range(n)]))

count = 1

resultp = 0
resultq = 0

for pp in plist:
    if(list(pp) == p):
        resultp = count
    if (list(pp) == q):
        resultq = count
    count += 1

print(abs(resultp - resultq))

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

def factorial(x):
    if x > 1:
        return factorial(x-1) * x
    else:
        return 1

def remained(num, remain_list):
    return sum([item < num for item in remain_list])

order_p, order_q = 1, 1
remain_p, remain_q = list(range(1, N+1)), list(range(1, N+1))

for i in range(N-1):
    order_p += remained(p[i], remain_p) * factorial(N - i - 1)
    order_q += remained(q[i], remain_q) * factorial(N - i - 1)
    remain_p.remove(p[i])
    remain_q.remove(q[i])

print((order_p - order_q) if (order_p - order_q > 0) else (order_q - order_p))