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):
import copy

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

def hoge(numbers, s, n_list):

    for i in range(len(numbers)):
        copy_numbers = copy.deepcopy(numbers)
        ss = s+copy_numbers.pop(i)
        if len(copy_numbers) > 0:
            hoge(copy_numbers, ss, n_list)
        else:
            n_list.append(int(ss))

n_list = []
for i in range(n):
    number_list = [str(i) for i in range(1, n+1)]
    s = number_list.pop(i)
    hoge(number_list, s, n_list)

n_list.sort()

ans = abs((n_list.index(p) + 1) - (n_list.index(q) + 1))
print(ans)

Solution (Python):
N=int(input())
P_=list(map(int, input().split()))
Q_=list(map(int, input().split()))
import numpy as np

def stair(N):
  ans=1
  for i in range(1,N+1):
    ans*=i
  return ans

def calc_dict(Q):
  re=list(range(1,len(Q)+1))
  ans=1
  for j in range(len(Q)-1):
    
    if Q[j]!=re[0]:
      a=np.where(np.array(re)<Q[j], 1, 0).sum()
      
      ans+=a*stair(len(Q[(j+1):]))
      
      re.remove(Q[j])
    else:
      re.remove(Q[j])
  if ans==0:
    ans+=1
  return ans


print(abs(calc_dict(P_)-calc_dict(Q_)))

Solution (Python):
import math


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

    p_pos = get_pos(P)
    q_pos = get_pos(Q)
    if p_pos > q_pos:
        print(p_pos - q_pos)
    else:
        print(q_pos - p_pos)


def get_pos(arr):
    len_to_pattern = [0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
    p_pos = 0
    pos = len(arr) - 1
    first = len_to_pattern[pos]
    after = list(arr)
    after.sort()
    i = 0
    for p1 in arr:
        p_pos += first * after.index(p1)
        pos -= 1
        first = len_to_pattern[pos]
        i += 1
        after = arr[i:]
        after.sort()
    return p_pos


def get_max_len(l):
    v = l.sort(reverse=True)[0]
    return len(str(v))


if __name__ == "__main__":
    main()

Solution (Python):
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
A = B = 0
for i,v in enumerate(list(itertools.permutations(range(1,N+1))), 1):
    if list(v) == P:
        A = i
    elif list(v) == Q:
        B = i
        continue
    else:
        pass
print(abs(A-B) if A != 0 and B != 0 else 0)

Solution (Python):
import math
import itertools
n=int(input())

a=list(map(str,input().split()))
b=list(map(str,input().split()))

p=str(math.factorial(n))

a_list = [''.join(v) for v in itertools.permutations(a)]
a_int = [int(i) for i in a_list]
a_int.sort()

a_=[int(i) for i in a]
b_=[int(j) for j in b]
x="".join(a)
y="".join(b)

p_=a_int.index(int(x))+1
q_=a_int.index(int(y))+1

sum=abs(p_-q_)
print(sum)

Solution (Python):
import math


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

L = []
for i in range(N):
    L.append(math.factorial(N - i -1))



def return_num(numList):

    Flag = []
    for j in range(N):
        Flag.append(1)

    M = 0
    for k in range(N):
        
        Flag[numList[k] - 1] = 0
        M += sum(Flag[:numList[k]-1]) * L[k]


    return M+1



print(abs(return_num(p)-return_num(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 math
import bisect
n= int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
A=0
B=0
for i in range(n-1):
    an=bisect.bisect_left(sorted(a[i:]),a[i])
    
    A+= an *math.factorial(n-i-1)
    
    bn=bisect.bisect_left(sorted(b[i:]),b[i])

    B+= bn *math.factorial(n-i-1)
    

print(abs(A-B))

Solution (Python):
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
A = B = 0
for i,v in enumerate(list(itertools.permutations(range(1,N+1))), 1):
    if list(v) == P:
        A = i
    elif list(v) == Q:
        B = i
        continue
    else:
        pass

print(abs(A-B) if A != 0 and B != 0 else 0)

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

def check_order(k):
    res = 0
    for _ in range(n):
        if len(k) == 1:
            break
        s = k[0]
        c = 0
        for i in k:
            if s >= i:
                 c += 1
        k.pop(0)
        res += math.factorial(len(k)) * (c-1)
    return res

p_order = check_order(p)
q_order = check_order(q)

print(abs(p_order-q_order))

Solution (Python):
import math

n = int(raw_input())
p = raw_input().split()
pb = list(range(n))
q = raw_input().split()
qb = list(range(n))

ps = 0
qs = 0

for i in range(n - 1):
    p0 = pb.index(int(p[i]) - 1)
    pb.remove(int(p[i]) - 1)
    ps = (n - i - 1) * (ps + int(p0))

    q0 = qb.index(int(q[i]) - 1)
    qb.remove(int(q[i]) - 1)
    qs = (n - i - 1) * (qs + int(q0))

if qs - ps > 0:
    print qs - ps
else:
    print ps - qs

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

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

X=T.index(A)
Y=T.index(B)
print(abs(X-Y))

Solution (Python):
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
A = B = 0
for i,v in enumerate(list(itertools.permutations(range(1,N+1))), 1):
    if list(v) == P:
        A = i
    elif list(v) == Q:
        B = i
    else:
        pass

print(abs(A-B) if A != 0 and B != 0 else 0)

Solution (Python):
N = int(input())
listA = list(map(int, input().split()))
listB = list(map(int, input().split()))

def exc(n):
    if n == 0:
        return 1
    return n*exc(n-1)


def hatena(list_data, N):
    new_list = []
    index = 0
    for i in range(0, N):
        count = 0
        if list_data[i] == 1:
            new_list.append(1)
            continue
        else:
            for list_el in new_list:
                if list_data[i] > list_el:
                    count += 1

            index += (list_data[i]-1-count)*exc(N-1-i)
            new_list.append(list_data[i])
    return index

answer = hatena(listA, N) - hatena(listB, N)




if answer < 0:
    answer = -answer

print(answer)

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

P_zero=[i for i in range(1,N+1)]
Q_zero=[j for j in range(1,N+1)]
a=0
b=0
for i in range(N):
    x=N-(i+1)
    fx=math.factorial(x)
    dp=P_zero.index(P[i])
    dq=Q_zero.index(Q[i])
    a+=dp*fx
    b+=dq*fx
    P_zero.remove(P[i])
    Q_zero.remove(Q[i])

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

Solution (Python):
from itertools import permutations

N = int(input())
first = tuple(int(i) for i in input().split())
second = tuple(int(i) for i in input().split())

perm = list(permutations(range(1, N+1), N))
print(abs(perm.index(first) - perm.index(second)))

Solution (Python):
def factorial_cor(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact


N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
X=[0] *N
for idx in range(N):
    X[idx]=factorial_cor(N-1-idx)

Pp = 1
for idx in range(N - 1):
    count = 0
    for idy in range(idx):
        if (P[idx] > P[idy]):
            count+=1
    Pp += ((P[idx] - count - 1) if (P[idx] - count - 1) >= 0 else 0) * X[idx]
Qp = 1
for idx in range(N - 1):
    count = 0
    for idy in range(idx):
        if (Q[idx] > Q[idy]):
            count+=1
    Qp += ((Q[idx] - count - 1) if (Q[idx] - count - 1) >= 0 else 0) * X[idx]

print(abs(Pp-Qp))

Solution (Python):


import itertools
from itertools import permutations

def C():
    n = int(raw_input())
    p = list(map(int, raw_input().split()))
    q = list(map(int, raw_input().split()))
    a = 1
    f_a = True
    b = 1
    f_b = True
    for sel in itertools.permutations(range(1,n+1)):
        aa = 0
        bb = 0
        if f_a:
            for i in range(0,n):
                if sel[i] == p[i]:
                    aa = aa + 1
            if aa == n:
                f_a = False
            else:
                a = a + 1
        if f_b:
            for i in range(0,n):
                if sel[i] == q[i]:
                    bb = bb + 1
            if bb == n:
                f_b = False
            else:
                b = b + 1
    print abs(a - b)

if __name__ == '__main__':
    C()

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

def kaijo(i):
  x = i
  while i > 1:
    i -= 1
    x = x * i
  return x

nokori = list(range(1,N+1))
cnt = 0
for keta in range(1,N+1):


  nokori.sort()

  banme = nokori.index(P[keta-1])+1

  cnt = cnt + kaijo(N-keta) * (banme -1) + 1
  nokori.remove(P[keta-1])




nokori = list(range(1,N+1))
cntQ = 0
for keta in range(1,N+1):


  nokori.sort()

  banme = nokori.index(Q[keta-1])+1

  cntQ = cntQ + kaijo(N-keta) * (banme -1) + 1
  nokori.remove(Q[keta-1])
print(abs(cnt - cntQ))

Solution (Python):
N = int(input())
P = input().split()
Q = input().split()
R = [0,0,0,0,0,0,0,0,0]
j = 0
count = 0
sum_P = 0

def kaijo(x):
    if x == 1 or x == 0:
        return 1
    else:
        return x * kaijo(x - 1)

for i in range(N):
    R[int(P[i])] += 1
    for j in range(int(P[i])):
        if R[j+1] == 0:
            count += 1
    sum_P += kaijo(N - i - 1) * count
    count = 0
    j = 0

R = [0,0,0,0,0,0,0,0,0]
j = 0
count = 0
sum_Q = 0

for i in range(N):
    R[int(Q[i])] += 1
    for j in range(int(Q[i])):
        if R[j+1] == 0:
            count += 1
    sum_Q += kaijo(N - i - 1) * count
    count = 0
    j = 0

print(abs(sum_P - sum_Q))

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

def fact(n):
    s2=1
    while(n!=0):
        s2=s2*n
        n=n-1
    return(s2)

def count(A):
    s=0
    for i in range(0,N):
        B=sorted(A)
        key=[j for j,e in enumerate(B) if e==A[0]]
        flag=key[0]
        del(A[0])
        del(B[flag])
        s+=flag*(fact(N-1-i))
    return s

p=count(P)
q=count(Q)

if(p>q):
    print(p-q)
else:
    print(q-p)

Solution (Python):
import math

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

def min_seq(N):

    Seq = 0
    keta=1
    for i in range (N):
        num = N * keta
        Seq = Seq + num
        N=N-1
        keta=keta*10
    print(Seq)
    return Seq


def connect_PQ(A):
    A_Seq = []
    for i in range (N):
        A_Seq.append(A[i])
    A_Seq = ''.join(A_Seq)
    
    return A_Seq

def sort_seq(A, N):
    sort_num = 1
    for i in range(N):
        alrady_used_num = 0
        for j in range(i):
            if (A[i] > A[j]):
                alrady_used_num = alrady_used_num + 1
        sort_num = sort_num + (A[i]-1-alrady_used_num)*math.factorial(N-1-i)
    
    return sort_num





P_sort_num = sort_seq(P, N)
Q_sort_num = sort_seq(Q, N)

result = abs(P_sort_num - Q_sort_num)
print(result)

Solution (Python):
import math

def gosaikutu(nums):
    numbers = list(range(1, len(nums)+1))
    gosa = [0]*len(nums)
    
    for i,number in enumerate(nums):
        gosa[i] = numbers.index(number)
        numbers.remove(number)
    
    return gosa
    
def nanbanme(gosa):
    nanban = 1
    ikutu = len(gosa)
    
    for j,value in enumerate(gosa):
        keisuu = math.factorial(ikutu - j - 1)
        
        if value is not 0:
            nanban += keisuu * value
    return nanban

n = input()
nums1 = list(map(int, input().split(' ')))
nums2 = list(map(int, input().split(' ')))

banme1 = nanbanme(gosaikutu(nums2))
banme2 = nanbanme(gosaikutu(nums1))
ans = banme1 - banme2
if ans < 0:
    print(-ans)
else:
    print(ans)

Solution (Python):
import math

N = int(input())

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


def rank(l):
    ll = sorted(l)
    return ll.index(l[0])

ans1 = 0
ans2 = 0
for i in range(N-1):
    ans1 = ans1 + rank(P) * math.factorial(N - i - 1)
    P = P[1:N]
    ans2 = ans2 + rank(Q) * math.factorial(N - i - 1)
    Q = Q[1:N]

if (ans1 - ans2 < 0):
    print(ans2 - ans1)
else:
    print(ans1 - ans2)

Solution (Python):
import itertools

n = int(input())

p = list(map(int,input().split()))
q = list(map(int,input().split()))
x = sorted(p)
ans = int(0)

P = tuple(p)
ans1 = int(0)

Q = tuple(q)
ans2 = int(0)

for i in itertools.permutations(x, n):
    if P == i:
        break
    else:
        ans1 += 1

for i in itertools.permutations(x, n):
    if Q == i:
        break
    else:
        ans2 += 1

ans = ans1-ans2

print(abs(ans))

Solution (Python):
N = int(input())
Ps = list(map(int, input().split()))
Qs = list(map(int, input().split()))


cnt = 0
start = 0
end = 0
is_hit = False
for i in range(1,N+1):
    for j in range(1,N+1):
        if j in [i]:
            continue
        if N == 2:
            cnt += 1
        if [i, j] == Ps:
            start = cnt
        if [i, j] == Qs:
            end = cnt
        if start * end > 0:
            is_hit = True
            break
        if N == 2:
            continue
        for k in range(1,N+1):
            if k in [i, j]:
                continue
            if N == 3:
                cnt += 1
            if [i, j, k] == Ps:
                start = cnt

            if [i, j, k] == Qs:
                end = cnt
            if start * end > 0:
                is_hit = True
                break
            if N == 3:
                continue
            for l in range(1,N+1):
                if l in [i, j, k]:
                    continue
                if N == 4:
                    cnt += 1
                if [i, j, k, l] == Ps:
                    start = cnt

                if [i, j, k, l] == Qs:
                    end = cnt

                if start * end > 0:
                    is_hit = True
                    break

                if N == 4:
                    continue
                for m in range(1, N+1):
                    if m in [i, j, k, l]:
                        continue
                    if N == 5:
                        cnt += 1
                    if [i, j, k, l, m] == Ps:
                        start = cnt
                    if [i, j, k, l, m] == Qs:
                        end = cnt

                    if start * end > 0:
                        is_hit = True
                        break

                    if N == 5:
                        continue
                    for n in range(1, N+1):
                        if n in [i, j, k, l, m]:
                            continue
                        if N == 6:
                            cnt += 1
                        if [i, j, k, l, m, n] == Ps:
                            start = cnt
                        if [i, j, k, l, m, n] == Qs:
                            end = cnt
                        if start * end > 0:
                            is_hit = True
                            break
                        if N == 6:
                            continue
                        for o in range(1, N+1):
                            if o in [i, j, k, l, m, n]:
                                continue
                            if N == 7:
                                cnt += 1
                            if [i, j, k, l, m, n, o] == Ps:
                                start = cnt
                            if [i, j, k, l, m, n, o] == Qs:
                                end = cnt
                            if start * end > 0:
                                is_hit = True
                                break
                            if N == 7:
                                continue
                            for p in range(1, N+1):
                                if p in [i, j, k, l, m, n, o]:
                                    continue
                                if N == 8:
                                    cnt += 1
                                if [i, j, k, l, m, n, o, p] == Ps:
                                    start = cnt
                                if [i, j, k, l, m, n, o, p] == Qs:
                                    end = cnt
                                if start * end > 0:
                                    is_hit = True
                                    break
                            if is_hit:
                                break
                        if is_hit:
                            break
                    if is_hit:
                        break
                if is_hit:
                    break
            if is_hit:
                break
        if is_hit:
            break
    if is_hit:
        break

print(abs(end - start))

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


def main():
    sc = Scan()
    N = sc.intarr()[0]
    P = sc.intarr()
    Q = sc.intarr()
    p_idx = -1
    q_idx = -1
    roop = 0
    array = []
    for i in range(1, N+1):
        array.append(i)
    pp = perm(array)
    for p in pp:
        if p == P:
            p_idx = roop
        if p == Q:
            q_idx = roop
        roop += 1

    print(abs(p_idx-q_idx))


def perm(p):
    if len(p) == 1:
        return [p]
    else:
        s = []
        for i in range(len(p)):
            q = p[i]
            r = perm(p[:i]+p[i+1:])
            for t in r:
                s.append([q] + t)
        return s


class Scan():

    def intarr(self):
        num_array = list(map(int, input().split()))
        return num_array

    def intarr_ver(self, n):
        return [int(input()) for _ in range(n)]

    def strarr(self):
        line = input()
        array = line.split(' ')
        array[-1] = array[-1].strip('\n')
        return array


def display(array):
    for a in range(len(array)):
        if len(array) - a != 1:
            print(array[a], end=' ')
        else:
            print(array[a])


def gcd(a, b):  
    while b:
        a, b = b, a % b
    return a


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


main()

Solution (Python):
import numpy
import itertools
N=int(input())
p=list(map(int, input().split()))
q=list(map(int, input().split()))
value = 1
count=0
second_box =[]
box = [i for i in range(1,N+1)]
value = list(itertools.permutations(box))

def func(i):
    rs = 0
    for j in range(N):
        rs += i[j] * 10**(N-j-1)
    return rs 
  
second_box = [ func(i) for i in value]



third_box = sorted(second_box,reverse=False)

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

Solution (Python):
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
L=[]
sum=0
for i in range(1,N+1):
    L.append(i)
M=list(itertools.permutations(L))
for i in M:
    if P == i:
        seterP=(M.index(i))
    if Q == i:
        seterQ=(M.index(i))
if seterP>=seterQ:
    print(seterP-seterQ)
else:
    print(seterQ-seterP)

Solution (Python):
import itertools 

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

arrayForPerm = []

for i in range(1,N+1):
  arrayForPerm.append(i)
  
perm = itertools.permutations(arrayForPerm)
newPerm = list(perm)

for i in range(len(newPerm)):
  if list(newPerm[i]) == P:
    A = i + 1
  if list(newPerm[i]) == Q:
    B = i + 1

result = A - B

print(abs(result))

Solution (Python):
import itertools 

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

arrayForPerm = []

for i in range(1,N+1):
  arrayForPerm.append(i)
  
perm = itertools.permutations(arrayForPerm)
newPerm = list(perm)

for i in range(len(newPerm)):
  if list(newPerm[i]) == P:
    A = i + 1
  if list(newPerm[i]) == Q:
    B = i + 1

result = A - B

print(abs(result))

Solution (Python):
n = int(input())
x = map(int, input().split()[:n-1])
y = map(int, input().split()[:n-1])
if x == y:
    print(0)
else:
    l1 = [i for i in range(1, n+1)]
    l2 = list(l1)
    def fact(k):
        return 1 if k <= 1 else k * fact(k-1)

    def get_lex_order(n, l, z):
        t = 0
        for i, m in enumerate(z):
            k = l.index(m)
            l.remove(m)
            t += k * fact(n - i - 1)
        return t + 1
    print(abs(get_lex_order(n, l1, x) - get_lex_order(n, l2, y)))

Solution (Python):
import itertools
import re

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

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

conv =[]
for v in itertools.permutations(n_list, n):
    conv.append(v)

for i, j in enumerate(conv):
    if p == j:
        p_ind = i + 1

for i, j in enumerate(conv):
    if q == j:
        q_ind = i + 1

print(abs(p_ind - q_ind))

Solution (Python):
import sys
from functools import reduce
import itertools


input = sys.stdin.readline

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

if (P == Q):
    print(0)
else:
    res = list(filter(lambda t: t[1] == P or t[1] == Q, enumerate(itertools.permutations(range(1, N + 1)))))

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

Solution (Python):
import itertools 

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

arrayForPerm = []

for i in range(1,N+1):
  arrayForPerm.append(i)
  
perm = itertools.permutations(arrayForPerm)
newPerm = list(perm)

for i in range(len(newPerm)):
  if list(newPerm[i]) == P:
    A = i + 1
  if list(newPerm[i]) == Q:
    B = i + 1

result = A - B

print(abs(result))

Solution (Python):

import numpy as np

n = int(input())
p = np.array(input().split(), dtype='int')
q = np.array(input().split(), dtype='int')

kaijou = np.array([1, 2, 6, 24, 120, 720, 5040])

a = 1
b = 1

num_array = np.arange(1, n + 1)
for i in range(n - 1):
    for j in range(n - i):
        if p[i] == num_array[j]:
            k = j
    a += k * kaijou[n - i - 2]
    num_array = np.delete(num_array, k)


num_array = np.arange(1, n + 1)
for i in range(n - 1):
    for j in range(n - i):
        if q[i] == num_array[j]:
            k = j
    b += k * kaijou[n - i - 2]
    num_array = np.delete(num_array, k)

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

Solution (Python):
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
def fact(a):
    if a == 1:
        return 1
    else: return a * fact(a-1)
def orde(s):
    y = 1
    for i in range(len(s)-1):
        y += fact(len(s)-i-1) * (s[i]-1)
        for j in range(i, len(s)):
            if s[j] > s[i]:
                s[j] -= 1
    return y
print(abs(orde(p)-orde(q)))

Solution (Python):
import itertools

N = list(map(int, input().split()))
permutation_P = tuple(map(int, input().split()))
permutation_Q = tuple(map(int, input().split()))

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

dictionaly = list(itertools.permutations(data))
dic_size = len(dictionaly)

for j in range(0, dic_size):
    if permutation_P == dictionaly[j] and permutation_Q == dictionaly[j]:
        a = j + 1
        b = j + 1
    elif permutation_P == dictionaly[j]:
        a = j + 1
    elif permutation_Q == dictionaly[j]:
        b = j + 1

if (a - b) >=  0:
    print(a - b)
elif (a - b) < 0:
    print(-1 * (a - b))

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

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

def hoge(n,lis):
    for i in range(len(lis)):
        if n==lis[i]:
            return i
        
def cnt(lis):
    
    l = list(range(1,len(lis)+1)) 
    ret = 1
    for i in range(len(lis)-1):
        ret += (hoge(int(lis[i]),l)) * fact(len(l)-1)

        l.remove(lis[i])

    return ret

print(abs(cnt(P) - cnt(Q)))

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

from itertools import permutations

t = [i for i in range(1, N+1)]
r = list(permutations(t))




i1 = r.index(P)
i2 = r.index(Q)
print(abs(i1-i2))

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

def kaijou(n):
    s = 1
    for i in range(n):
        s *= i+1
    return s

def jisyo(L):
    l = 0
    k = len(L)
    for i in range(k):
        n = L.pop(0)
        l += kaijou(len(L))*(n-1)
        for m in range(len(L)):
            if L[m] > n:
                L[m] -= 1
    return l+1

print(abs(jisyo(P)-jisyo(Q)))

Solution (Python):


import itertools

n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
a = b  = count= 0

org = sorted(p)

for v in itertools.permutations(org,n):
    count += 1
    
    if list(v)==p:
        a = count
    
    if list(v)==q:
        b = count

print(abs(a - b))

Solution (Python):
def kaijo(x):
  if x<=1:
    return 1
  elif x==2:
    return 2
  elif x==3:
    return 6
  elif x==4:
    return 24
  elif x==5:
    return 120
  elif x==6:
    return 720
  elif x==7:
    return 5040
  elif x==8:
    return 5040*8
  else:
    return 0

N=int(input())
s=input().split(" ")
P=[int(ss) for ss in s]
s=input().split(" ")
Q=[int(ss) for ss in s]

Ls=[i+1 for i in range(N)]
rank=0
for i in range(N):
  for j in range(len(Ls)):
    if Ls[j]==P[i]:
      a=j
      Ls.pop(j)
      break
  rank+=kaijo(N-i-1)*a
rp=rank

rank=0
Ls=[i+1 for i in range(N)]

for i in range(N):
  for j in range(len(Ls)):
    if Ls[j]==Q[i]:
      a=j
      Ls.pop(j)
      break
  rank+=kaijo(N-i-1)*a
rq=rank

print(abs(rp-rq))

Solution (Python):
r = int(input())
tp = tuple(map(int,input().split()))
tq = tuple(map(int,input().split()))

import itertools

p, q = 0, 0 
for i, ti in enumerate(itertools.permutations(range(1,r+1))):
    if tp == ti:
        p = i        
    if tq == ti:
        q = i
    if p * q > 0:
        break

print(abs(p-q))

Solution (Python):
import math

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
  
a = list(range(1, n+1))
b = list(range(1, n+1))
nump = 1
numq = 1

for i in range(n):
  nump += a.index(p[i]) * math.factorial(n-(i+1))
  a.remove(p[i])

for i in range(n):
  numq += b.index(q[i]) * math.factorial(n-(i+1))
  b.remove(q[i])

print(abs(nump - numq))

Solution (Python):
import math
import copy

n = int(input())
ls_p = list(map(int, input().split()))
ls_q = list(map(int, input().split()))

ls_pc = copy.copy(ls_p)
ls_qc = copy.copy(ls_q)

s = 0
t = 0

ansp = 0
ansq = 0

for i in range(n):
    s = ls_pc[i]
    ls_ps = sorted(ls_p)
    j = ls_ps.index(s)
    ansp += math.factorial(n - i - 1) * j
    ls_p.remove(s)
    
    t = ls_qc[i]
    ls_qs = sorted(ls_q)
    k = ls_qs.index(t)
    ansq += math.factorial(n - i - 1) * k
    ls_q.remove(t)

print(abs(ansp - ansq))

Solution (Python):
import itertools

n = int(input())
li_p = input().split()
li_q = input().split()

li_p = tuple(li_p)
li_q = tuple(li_q)

li_min = sorted(li_p)
list_all = []

for i in itertools.permutations(li_min):
    list_all.append(i)

for i in range(0, len(list_all)):
    if list_all[i] == li_p:
        count_p = i
    if list_all[i] == li_q:
        count_q = i

print(abs(count_p - count_q))

Solution (Python):
import itertools

N = int(input())
T = list(range(1,N+1))
S = list(itertools.permutations(T, N))
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]

for i in range(len(S)):
    if tuple(P) == S[i]:
        A = i
    if tuple(Q) == S[i]:
        B = i
print(abs(A-B))

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


a = list(itertools.permutations(p))
b = list(itertools.permutations(q))

a.sort()
b.sort()

ans1 = a.index(p) + 1
ans2 = b.index(q) + 1

print(abs(ans1 - ans2))

Solution (Python):
from itertools import permutations 

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

perm = list(permutations(range(1, N+1), N))
print(abs(perm.index(P) - perm.index(Q)))

Solution (Python):
n = int(input())
p = [int(v) for v in input().split()]
q = [int(v) for v in input().split()]

def index_of(array, v):
    for i in range(len(array)):
        if v == array[i]:
            return i
    return -1

def perm(v):
    p = 1
    for i in range(2, v+1):
        p *= i
    return p

memo = [1] * (n+1)
for i in range(1, n+1):
    memo[i] = perm(i)
    

def to_n(array):

    m = 0
    sa = sorted(array)
    while len(array) > 0:
        v = array.pop(0)
        index = index_of(sa, v)
        k = len(array)
        
        m += index * memo[k]

        if k == 0:
            break
        sa = sorted(array)

    return m

a = to_n(p)


b = to_n(q)

print(abs(a - b))

Solution (Python):
import math
import itertools

N = int(input())

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

tP = tuple(P)
tQ = tuple(Q)
ord_P = 0 
ord_Q = 0 
cnt = 1
Num = []


for i in itertools.permutations(range(1,N+1)): 
    if i == tP:
        ord_P = cnt
    if i == tQ:
        ord_Q = cnt
    cnt += 1
    
print(abs(ord_P - ord_Q))

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

import itertools
a = tuple(i for i in range(1,n+1))
x = list(itertools.permutations(a))

px = x.index(p)
qx = x.index(q)
print(abs(px-qx))

Solution (Python):
import math
 
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
 
p_sort = sorted(p)
q_sort = sorted(q)
 
p_number = 1
q_number = 1
 
k = 0
for i in p:
  k += 1
  i_index = p_sort.index(i)
  p_number += i_index * math.factorial(n-k)
  p_sort.remove(i)
k = 0
for i in q:
  k += 1
  i_index = q_sort.index(i)
  q_number += i_index * math.factorial(n-k)
  q_sort.remove(i)
answer = abs(p_number - q_number)
print(answer)

Solution (Python):
r = int(input())
tp = tuple(map(int,input().split()))
tq = tuple(map(int,input().split()))

import itertools

for i, ti in enumerate(itertools.permutations(range(1,r+1))):
    if tp == ti:
        p = i
        break

for i, ti in enumerate(itertools.permutations(range(1,r+1))):
    if tq == ti:
        q = i
        break

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