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

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

def factorial(n):
    if n < 2:
        return 1
    ret = 1
    for i in range(2, n + 1):
        ret *= i
    return ret

import itertools
seq = list(map(lambda x: x + 1, list(range(n))))
ptr = list(itertools.permutations(seq))

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

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

def kaisa(x):
  a = 1
  for i in range(1,x + 1,1):
    a += a *i
  return a 
    
a_ = 1
b_ = 1

for i in range(1,n,1):
  a_ += sorted(a).index(a[0]) * kaisa(n-1-i)
  del a[0]
  b_ += sorted(b).index(b[0]) * kaisa(n-1-i)
  del b[0]
  
print(abs(a_ - b_))

Solution (Python):
import itertools
num = int(input())
p = tuple(input().split())
q = tuple(input().split())
lister = [str(s) for s in range(1,num+1)]
comb = list(itertools.permutations(lister))
memory1 = 0
memory2 = 0
for t in range(len(comb)):
    if p == comb[t]:
        memory1 = t+1
    if q == comb[t]:
        memory2 = t+1
print(abs(memory1-memory2))

Solution (Python):
def cnt(kurai, num, detalist):
    jun_i = (num - 1 - sum(detalist[:(num-1)])) * kaijo[kurai-1]
    return jun_i

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

kaijo = [1, 1, 2, 6, 24, 120, 720, 5040]
detalist_p = [0] * n
detalist_q = [0] * n

pno = 1
qno = 1
for i in range(n-1):
    pno += cnt(n-i, P[i], detalist_p)
    detalist_p[P[i]-1] = 1

    qno += cnt(n-i, Q[i], detalist_q)
    detalist_q[Q[i]-1] = 1

print(abs(pno - qno))

Solution (Python):
import math
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
x = 0
y = 0
cnt=0
for i in range(n):
  for l in range(i):
    if p[i] > p[l]:
      cnt += 1
  x += (p[i] - 1 - cnt)*(int(math.factorial(n - 1 - i)))
  cnt = 0
for i in range(n):
  for l in range(i):
    if q[i] > q[l]:
      cnt += 1
  y += (q[i] - 1 - cnt)*(int(math.factorial(n - 1 - i)))
  cnt = 0
print(abs(x-y))

Solution (Python):
import sys
import math
import bisect
stdin = sys.stdin
mod = 10**9 + 7

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
sa = lambda h: [list(map(int, stdin.readline().split())) for i in range(h)]

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

n = ni()

p = na()
q = na()
def check(pq):
    ans = factorial(n)
    a = list(range(1,n+1))
    for i in range(n):
        l = n - i
        pqi = pq[i]
        index = a.index(pqi)
        ans -= factorial(max(l-1, 0)) * max(l-index, 0)
        a.remove(pqi)
    return ans
print(abs(check(p) - check(q)))

Solution (Python):
import math

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

count = 0

def keisan(t):
    num = []
    q = 0
    c = 0
    tmp = 1
    while q < N:
        if int(t[q]) > tmp and (tmp in num) is False:
            c += math.factorial(N - q - 1)
            tmp += 1
        elif int(t[q]) == tmp:
            q += 1
            num.append(tmp)
            tmp = 1
        else:
            tmp += 1
    return c


count += abs(keisan(P) - keisan(Q))

print(count)

Solution (Python):
number_select = int(input())
A = list(map(str,input().split()))
B = list(map(str,input().split()))
A_total = 0
B_total = 0
listA = []
def pattern(a):
    b = 1
    for r in range(1,a+1):
        b = b * r
    return b
def list_A(a):
    for i in range(1,a+1):
        listA.append(str(i))
list_A(number_select)
for i in range(number_select-1):
    A_total += listA.index(A[i]) * pattern(number_select-i-1)
    listA.remove(A[i])
listA.clear()
list_A(number_select)
for r in range(number_select-1):
    B_total += listA.index(B[r]) * pattern(number_select-r-1)
    listA.remove(B[r])
print(abs(A_total-B_total))

Solution (Python):
from collections import defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys
import random
import itertools
import math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt


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


def LF(): return list(map(float, input().split()))


def LI_(): return list(map(lambda x: int(x)-1, input().split()))


def II(): return int(input())


def IF(): return float(input())


def LS(): return list(map(list, input().split()))


def S(): return list(input().rstrip())


def IR(n): return [II() for _ in range(n)]


def LIR(n): return [LI() for _ in range(n)]


def FR(n): return [IF() for _ in range(n)]


def LFR(n): return [LI() for _ in range(n)]


def LIR_(n): return [LI_() for _ in range(n)]


def SR(n): return [S() for _ in range(n)]


def LSR(n): return [LS() for _ in range(n)]


def gcd(x, y):
    if y == 0:
        return x
    return gcd(y, x % y)


def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]


def sosu(x):
    for i in range(2, int(sqrt(x)+1)):
        if x % i == 0:
            return False
    return True


mod = 1000000007
inf = float('INF')


def A():
    K, X= LI()

    if (500*K>=X):
        print('Yes')
    else:
        print('No')


    return




def B():
    N=II()
    S=input().rstrip()
    ans=0
    s=0
    for i in S:
        if (i=="A" and S[s+1]=='B' and S[s+2]=='C'):
            ans+=1
        s+=1
    print(ans)



    return




def true():
    S = input()
    S = S[:-1]

    tmp = 0
    for x in range(1 << (len(S)-1)):
        func = S[-1]
        for i in range(len(S)-1):
            if(x & (1 << i)):
                tmp += int(func)
                func = S[-2-i]
            else:
                func = S[-2-i]+func
        tmp += int(func)
    print(tmp)

    return


def flagcounter(x):
    if (x == 0):
        return 0
    return flagcounter(x >> 1)+(x & 1)

def jisyo(P):
    i=1
    S = sorted(P)
    X=0
    N=len(P)
    for p in P:
    
        X+=((S.index(p)+1) * (math.factorial(N-i)))-1
        
        S.remove(p)
        if len(S)==1:
            break
        i+=1
    return X

def C():
    N=II()
    P=LI()
    Q=LI()

    X=jisyo(P)
    Y=jisyo(Q)


    print(abs(X-Y))
        
    return



def D():
    N, K = LI()
    R, S, P = LI()
    T=list(input().rstrip())
    ans = 0
    for j in range(K):
        if T[j] == 'r':
            ans += P
        if T[j] == 'p':
            ans += S
        if T[j] == 's':
            ans += R
    j = 0
    rps=['r','p','s']

    for i in range(K, N):
        if T[j] == T[i]:
            if i+K>=N:
                j += 1
                continue
            T[i]=rps[rps.index(T[i+K])-1]
            j += 1
            continue
        if T[i] == 'r':
            ans += P
        if T[i] == 'p':
            ans += S
        if T[i] == 's':
            ans += R
        j += 1
    print(ans)
    return


def Dsyakutori():

    N, K = LI()
    A = LI()
    MAX = sum(A)
    if MAX < K:
        print(0)
        return
    Temp = MAX
    ans = 1
    for i in range(N):
        Temp = Temp-A[i]
        if (Temp >= K):
            ans += 1
        else:
            T = Temp+A[i]
            break
    Temp = T
    ckeep = N
    for k in range(N):
        c = N-1
        i -= 1
        Temp = T

        for j in range(N):
            Temp = Temp-A[c]
            if (Temp >= K):
                ans += 1

            elif(c < ckeep and i >= 0):
                ans += i
                ckeep = c
                break
            else:
                ckeep = c
                break
            c -= 1
        if i < 0:
            break
        T = T+A[i]
    print(ans)

    return




def E():
    N, M= LI()
    A = LI()
    A.sort(reverse=True)
    B=[0]*(N+1)
    for i in range(1,N+1):
        B[i]=B[i-1]+A[i-1]
    D=[0]*(2*10**5+1)
    for i in range(N):
        D[A[i]]+=1
    for i in range(len(D)-1,0,-1):
        D[i-1]+=D[i]
    l=-1
    r=2*10**5+1
    while r-l>1:
        m=(l+r)//2
        s=0
        for i in range(N):
            s+=D[max(1,m-A[i])]
        if s>=M:
            l=m
        else:
            r=m
    ans=0
    s=0
    for i in range(N):
        v=max(0,r-A[i])
        t=max(0,min(D[v],M-s))
        ans+=B[t]+t*A[i]
        s+=t
    ans+=l*(M-s)
    print(ans)

    
    return




def F():
    N, M = LI()

    value = [0] * M
    power = [0] * M
    for i in range(M):
        a, b = LI()
        value[i] = a
        c = LI()
        L = ['0'] * N
        for k in c:
            L[k - 1] = '1'
        bint = ''.join(L)
        power[i] = int(bint, 2)
    bint = ''.join(list(['1'] * N))
    dp = [inf] * (int(bint, 2)+1)
    t = 0
    cost = 0

    dp[0] = 0
    for s in range(int(bint, 2) + 1):
        for i in range(M):
            t = s | power[i]
            cost = dp[s] + value[i]
            dp[t] = min(dp[t], cost)
    print(-1) if(dp[-1] == inf) else print(dp[-1])

    return

    



def solution(S):
    
    N = len(S)

    pass



if __name__ == '__main__':

    C()

Solution (Python):
import math
import numpy as np

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

a = 1
a_list = list(np.arange(N) + 1)
for i in range(N - 1):
    a += a_list.index(P[i]) * math.factorial(N - (i + 1))
    a_list.remove(P[i])
    
b = 1
b_list = list(np.arange(N) + 1)
for j in range(N):
    b += b_list.index(Q[j]) * math.factorial(N - (j + 1))
    b_list.remove(Q[j])
    
print(abs(a - b))

Solution (Python):
import math

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

a = 1
b = 1
Pmin = sorted(P)
Qmin = sorted(Q)

for i in range(N-1) :
  Porder = Pmin.index(P[i])
  a += Porder * math.factorial(N - i - 1)
  Pmin.pop(Porder)

for i in range(N-1) :
  Qorder = Qmin.index(Q[i])
  b += Qorder * math.factorial(N - i - 1)
  Qmin.pop(Qorder)

ans = a-b

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

Solution (Python):
import itertools

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

all_list = list(itertools.permutations(p))
all_list.sort()

p_ans = 0
q_ans = 0

for i in range(len(all_list)):
    if list(all_list[i]) == p:
        p_ans = i
    if list(all_list[i]) == q:
        q_ans = i
print(abs(p_ans - q_ans))

Solution (Python):
import itertools

N=int(input())
first=""
for i in range(N):
    first+=str(i+1)
P=tuple(map(str,input().split()))
Q=tuple(map(str,input().split()))

A=list(itertools.permutations(first))

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

print(abs(p-q))

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

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

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

po = 0
for i in range(n):
    po += f(n-i-1)*nlist.index(p[i])
    nlist.remove(p[i])
po+=1
nlist = list(range(1, n+1))
qo = 0
for i in range(n):
    qo += f(n-i-1)*nlist.index(q[i])
    nlist.remove(q[i])
qo+=1
print(abs(po-qo))

Solution (Python):
import itertools
import math

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

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

for i in range(math.factorial(N)):
  if list(l[i]) == p:
    a = i
    break
    
for i in range(math.factorial(N)):
  if list(l[i]) == q:
    b = i
    break

print(abs(a-b))

Solution (Python):
def dictionary_order(Xs, n):
  ascend = [i+1 for i in range(n)]

  order = 1
  for i, x in enumerate(Xs):
    order += ascend.index(x) * factorial(n-1-i)
    ascend.remove(x)
  return order

def factorial(n):
  out = 1
  for i in range(2, n+1):
    out *= i
  return out

def main():
  N = int(input())
  Ps = list(map(int, input().split()))
  Qs = list(map(int, input().split()))
  if Ps == Qs:
    print(0)
  else:
    P_order = dictionary_order(Ps, N)
    Q_order = dictionary_order(Qs, N)
    print(abs(P_order-Q_order))
  
if __name__ == '__main__':
  main()

Solution (Python):
import math

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

p = 0
nf = math.factorial(N)
X = [False]*N
for i in range(N):
    nf //= (N-i)
    x = X[:P[i]].count(True)
    p += nf * (P[i]-1-x)
    X[P[i]-1] = True

q = 0
nf = math.factorial(N)
X = [False]*N
for i in range(N):
    nf //= (N-i)
    x = X[:Q[i]].count(True)
    q += nf * (Q[i]-1-x)
    X[Q[i]-1] = True

print(abs(p-q))

Solution (Python):
import itertools

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

l = list(range(1, n+1))
m = itertools.permutations(l,len(l))
_list = []
for i in m:
    _list.append(i)
print(abs(_list.index(p)-_list.index(q)))

Solution (Python):
import math
N = int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]

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

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

B = input().split(' ')
B = [int(j) for j in B]

string=""

for i in range (1,N+1):
    string+=str(i)

def permutation(lst): 
    if len(lst) == 0: 
        return [] 
    if len(lst) == 1: 
        return [lst] 
    l = []
    for i in range(len(lst)): 
       m = lst[i] 
       remLst = lst[:i] + lst[i+1:] 
       for p in permutation(remLst): 
           l.append([m] + p) 
    return l 

data = list(string)
permut_int=[]

for p in permutation(data): 
    permut_int.append([int(i) for i in p])

A_index = permut_int.index(A)+1
B_index = permut_int.index(B)+1

print(abs(A_index-B_index))

Solution (Python):
import itertools

n = int(input())
a = list(range(1,n+1))
p = list(map(int, input().split()))
q = list(map(int, input().split()))
i = 1
ap = 0
aq = 0
for x in list(itertools.permutations(a)):
    if(list(x) == p):
        ap = i
    if(list(x) == q):
        aq = i
    i = i + 1

if(ap > aq):
    print(ap - aq)
    exit()
print(aq - ap)

Solution (Python):
import math
import itertools

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

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

Solution (Python):
import itertools

n = int(input())
a = ''.join(input().split())
b = ''.join(input().split())

nn=[]
ss=[]

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

for i in itertools.permutations(nn):
    ss.append(''.join(map(str,list(i))))

ss.sort()

ai=ss.index(a)+1
bi=ss.index(b)+1

print(abs(ai-bi))

Solution (Python):


def swap(a, i, j):
    tmp = a[i]
    a[i] = a[j]
    a[j] = tmp

def next_permutation(a):
    n = len(a)
    if n == 0 or n == 1:
        return False
    kFound = False
    for k in reversed(range(n - 1)):
        if a[k] < a[k + 1]:
            kFound = True
            break
    if not kFound:
        return False

    for l in reversed(range(n)):
        if a[k] < a[l]:
            break
    swap(a, k, l)
    return a[:k + 1] + [i for i in reversed(a[k + 1:])]

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
a = []
for i in range(1,n+1):
    a.append(i)
flag = 0
s = 0
t = 0
u = 1
while flag < 2:
    if p == a:
        s = u
        flag += 1
    if q == a:
        t = u
        flag += 1
    a = next_permutation(a)
    u += 1
if s - t >= 0:
    print(s - t)
else:
    print(t - s)

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

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

def answer(P):
    l = list(range(1, len(P)+1))
    ans = 0
    for pi in P:
        if len(l) <= 2:
            ans += sum([i<pi for i in l])+1
            break
        else:
            ans += sum([i<pi for i in l]) * Fac(len(l)-1)
            l.remove(pi)
    return ans

print(abs(answer(P)-answer(Q)))

Solution (Python):
import itertools

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

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

for i in num:
    if i == string1:
        a = count
    if i == string2:
        b = count
    count += 1

print(abs(a-b))

Solution (Python):
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
P=["abcdefgh"[i-1] for i in p]
Q=["abcdefgh"[i-1] for i in q]
P=tuple(P)
Q=tuple(Q)
import itertools
R=list(itertools.permutations("abcdefgh"[:n]))
print(abs(R.index(P)-R.index(Q)))

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

l = list(range(1, n+1))
ll = []

def Count_Order(n, s):
    if n == 0:
        ll.append("".join(list(map(str, s))))
    else:
        for x in l:
            if not x in s:
                Count_Order(n-1, s+[x])

s = []
Count_Order(n, s)
print(abs(ll.index("".join(p)) - ll.index("".join(q))))

Solution (Python):
import itertools

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


Psotred  = sorted(P)
Qsotred  = sorted(Q)


A = list(itertools.permutations(Psotred, N))
B = list(itertools.permutations(Qsotred, N))


P_tap = tuple(P)
Q_tap = tuple(Q)

ans_P = 1
ans_Q = 1

for i in A:
    if i != P_tap:
        ans_P = ans_P +1
    elif i == P_tap:
        break

for i in B:
    if i != Q_tap:
        ans_Q = ans_Q +1
    elif i == Q_tap:
        break
        
print(abs((ans_Q)-(ans_P)))

Solution (Python):
import itertools

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

tp = tuple(p)
tq = tuple(q)

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

L = list(itertools.permutations(l))

tp_ind = L.index(tp)
tq_ind = L.index(tq)

ans = (tp_ind+1) - (tq_ind+1)
print(abs(ans))

Solution (Python):
import math
A=[]
B=[]
n=int(input())
for i in range(n):
    A.append(i+1)
    B.append(i+1)
SA=set(A)
SB=set(B)
F=[1,1]
f=1
for i in range(n-2):
    f*=i+2
    F.append(f)
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
p=0
for i in range(n-1):
    p+=(list(SA).index(P[i]))*F[n-i-1]
    s=[]
    s.append(P[i])
    SA^=set(s)
q=0
for i in range(n-1):
    q+=(list(SB).index(Q[i]))*F[n-i-1]
    s=[]
    s.append(Q[i])
    SB^=set(s)
print(abs(p-q))

Solution (Python):
from itertools import permutations
n=int(input())
p=tuple(map(int,input().split()))
q=tuple(map(int, input().split()))
lp = list(permutations(p, n))
lq = list(permutations(q, n))
lp.sort()
lq.sort()
a=lp.index(p)
b=lq.index(q)
print(abs(a-b))

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

ps = list(map(int,input().split()))

qs = list(map(int,input().split()))


a = 0
b = 0
r = 0
for i in range(n):
    if ps[i] == qs[i]:
        continue
    else:
        r = i
        break

ts = ps[r:]
ts.sort()

ns = list(itertools.permutations(ts))
m = len(ns)

for j in range(m):
    if list(ns[j]) == ps[r:]:
        a = j
        break

for l in range(m):
    if list(ns[l]) == qs[r:]:
        b = l
        break
    

print(abs(a-b))

Solution (Python):
"""
https://atcoder.jp/contests/abc150/tasks/abc150_c
"""
import numpy as np
from itertools import permutations


def calc(N: int, P: np.ndarray, Q: np.ndarray) -> int:
    pairs = list(permutations(range(1, N + 1)))
    pairs_dict = {tuple(v): i for i, v in enumerate(pairs)}
    return abs(pairs_dict[tuple(P)] - pairs_dict[tuple(Q)])


def load_input_as_int_array() -> np.ndarray:
    return np.array([int(v) for v in input().split(" ")])


def main() -> None:
    N, = load_input_as_int_array()
    P = load_input_as_int_array()
    Q = load_input_as_int_array()
    result = calc(N, P, Q)
    print(result)


main()

Solution (Python):
import itertools
import sys
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
a=[]
for i in range(1,n+1):
    a.append(i)
c=tuple(p)
d=tuple(q)
cnt=0
ans=0
ansl=0
if c==d:
    print(0)
    sys.exit()
for i in itertools.permutations(a):
    
    if c==i:
        ans=cnt
    elif d==i:
        ansl=cnt
    cnt+=1
print(abs(ans-ansl))

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

def ranking(n, numbers):
  tmp = list(range(1, n+1))
  ranking = []
  for n in numbers:
    index = tmp.index(n)
    ranking.append(index+1)
    tmp.pop(index)
  return ranking

def ranking2output(n, ranking):
  ret = 1
  x = 1
  for i in range(1, n+1):
    ret += (ranking[n-i]-1)*(x)
    x *= i
  return ret

a = ranking2output(n, ranking(n, p))
b = ranking2output(n, ranking(n, q))

print(abs(a-b))

Solution (Python):
from itertools import permutations

n = int(input())
Ps = list(map(int, input().split()))
Qs = list(map(int, input().split()))

a = 0
b = 0

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

for v in permutations(Rs, n):
    v_s = ''.join(list(map(str, v)))
    p_s = ''.join(list(map(str, Ps)))
    
    if v_s == p_s:
        break
    else:
        a += 1

for v in permutations(Rs, n):
    v_s = ''.join(list(map(str, v)))
    q_s = ''.join(list(map(str, Qs)))
    
    if v_s == q_s:
        break
    else:
        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()))

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

Solution (Python):
import itertools

n = int(input())
p = [i for i in input().split()]
q = [i for i in input().split()]
ans = 0

r = [str(i) for i in range(1,n+1)] 

x = [list(i) for i in itertools.permutations(r)]
  
if x.index(p) >= x.index(q):
  ans = x.index(p) - x.index(q)
else:
  ans = x.index(q) - x.index(p)

print(ans)

Solution (Python):
import itertools

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

num = []
for i in range(n):
    num.append(i+1)
    
l = itertools.permutations(num)

l2 = []
for i in l:
    youso = ''
    for j in range(n):
        youso += str(i[j])
    l2.append(youso)
    
p_n = l2.index(p)
q_n = l2.index(q)

print(abs(p_n-q_n))

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)))
a = perm.index(P)
b = perm.index(Q)

print(abs(a-b))

Solution (Python):
from itertools import permutations
n=int(input())
l = list(permutations(range(1, n+1))) 
s1=[int(x) for x in input().split()]
s2=[int(x) for x in input().split()]



pos1=l.index(tuple(s1))
pos2=l.index(tuple(s2))

print(abs(pos1-pos2))

Solution (Python):
import math
import itertools
a = int(input())
b = map(int,input().split(' '))
c = map(int,input().split(' '))
x = []
d = 0
e = 0
b = tuple(b)
c = tuple(c)
for i in range(a):
    x.append(i + 1)
y = itertools.permutations(x)
j = 1
for i in y:
    if i == b:
        d = j
    if i == c:
        e = j
    j += 1
print(abs(d - e))

Solution (Python):
import itertools

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

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

for i in num:
    if i == string1:
        a = count
    if i == string2:
        b = count
    count += 1

print(abs(a-b))

Solution (Python):
import math
import random
import itertools
N=int(input())
P=[int(x) for x in input().split()]
S=[int(x) for x in input().split()]

r=random.sample(range(1, N+1), k=N)


a=[]
p=0
s=0
for i in range(N):
    p+=P[i]*10**(N-i-1)
    s+=S[i]*10**(N-i-1)
for v in itertools.permutations(r, N):
    c=0
    for j in range(N):

        c+=v[j]*10**(N-j-1)
    a.append(c)
a.sort()
pin=a.index(p)
sin=a.index(s)
print(abs(pin-sin))

Solution (Python):
import itertools

N = int(input()) 
n = [i for i in range(1, N+1)]

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

P = ''.join(map(str,P))
Q = ''.join(map(str,Q))

num = 0
count = 1
A = 0
B = 0

for i in itertools.permutations(n):
  num = ''.join(map(str,i))
  if num == P:
    A = count
  if num == Q:
    B = count
  count += 1
  
print(abs(B-A))

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
  return n*fact(n-1)

def p_count(n, s, nums):
  if isinstance(nums, int):
    return 1
  idx=nums.index(s[0])
  nums.pop(idx)
  if len(nums) != 0:
    return (idx) * fact(n-1) + p_count(n-1, s[1:], nums)
  else:
    return 1
  
nl1=list(range(1,n+1))
nl2=list(range(1,n+1))
print(abs(p_count(n, p, nl1)-p_count(n, q, nl2)))

Solution (Python):
import itertools

N = int(input())
data = range(1,N+1)
p_list = list(itertools.permutations(data, N))

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

P_num = 0
Q_num = 0

for index,data in enumerate(p_list):
  if list(data) == P:
    P_num = index
  if list(data) == Q:
    Q_num = index
    
print(abs(P_num - Q_num))

Solution (Python):
import itertools
def main():
    N = int(input())
    P = list(map(int, input().split()))
    S = list(map(int, input().split()))
    count = 1
    if P == S:
        print(0)
    else:
        for i in itertools.permutations(list(range(1,N + 1))):
            if P == list(i):
                a = count
            elif S == list(i):
                b = count
            count += 1
        print(abs(a - b))
main()

Solution (Python):
import itertools
def main():
    n=int(input())
    P=tuple(map(int,input().split()))
    Q=tuple(map(int,input().split()))
    L=[i for i in range(1,n+1)]
    S=itertools.permutations(L,n)
    ans=0
    flag=1
    i=0
    if P==Q:
        print(0)
        exit()
    for s in S:
        i+=1
        if s==P or s==Q:
            if flag:
                ans -= i
                flag =0
            else:
                ans += i
                break
    print(ans)
main()

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

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

a = 1
for i in range(N-1):
    idx = l.index(P[i])
    a += idx * factorial(N-1-i)
    del l[idx]
    
b = 1
for i in range(N-1):
    idx = ll.index(Q[i])
    b += idx * factorial(N-1-i)
    del ll[idx]
    
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()))
a = 0
b = 0

for i in range(N-2):
  a += (P[i]-1-len([s for s in P[:i] if s < P[i]]))*factorial(N-i-1)
if P[N-2]>P[N-1]: a+=1

for i in range(N-2):
  b += (Q[i]-1-len([s for s in Q[:i] if s < Q[i]]))*factorial(N-i-1)  
if Q[N-2]>Q[N-1]: b+=1  
  
print(max(a,b)-min(a,b))

Solution (Python):
import itertools as it
a = int(input())
l = tuple(list(map(int,input().split())))
L = tuple(list(map(int,input().split())))

t = range(1,a+1)
T = list(it.permutations(t))

ans = abs (T.index(l)-T.index(L) )
print(ans)

Solution (Python):
import math
import itertools

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

nara = []
for v in itertools.permutations(list(range(1,N+1)), N):
  nara.append(list(v))

Pcount = nara.index(P)
Qcount = nara.index(Q)
print(abs(Pcount-Qcount))

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

def solve(x):
    if(x==1):
        return 1
    else:
        return x*solve(x-1)

def solve2(ls):
    x=ls[0]
    data=sorted(ls)
    return data.index(x)


ans1=0
ans2=0
for i in range(1,n):
    ans1+=solve(n-i)*solve2(p)
    del p[0]

    ans2+=solve(n-i)*solve2(q)
    del q[0]

print(abs(ans1-ans2))

Solution (Python):
import itertools

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

a = 0
b = 0
cnt = 0

tmp = sorted(P)

for x in itertools.permutations(tmp):
    cnt += 1

    if P == list(x):
        a = cnt

    if Q == list(x):
        b = cnt

print(abs(a - b))

Solution (Python):
import itertools
n = int(input())
a = []
for i in range(1,n+1):
    a.append(i)
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))

r = []
for z in list(itertools.permutations(a, n)):
    r.append(z)
print(abs((r.index(p)+1)-((r.index(q)+1))))

Solution (Python):
from collections import deque
def main():
    N = int(input())
    P = [str(int(n)-1) for n in input().split()]
    Q = [str(int(n)-1) for n in input().split()]
    P = "".join(P)
    Q = "".join(Q)
    q = deque([str(i) for i in range(N)])
    i = 0
    while len(q) > 0:
        i += 1
        s = q.popleft()
        if s == P:
            pp = i
        if s == Q:
            qq = i
        if len(s) == N:
            continue
        for i in range(N):
            if str(i) not in s:
                q.append(s + str(i))
    print(abs(pp-qq))
main()

Solution (Python):
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
import itertools
R = []
for i in range(1,N+1):
    R.append(i)
H = list(itertools.permutations(R))
a = 0
b = 0
for i in range(len(H)):
    h = H[i]
    r = []
    for j in range(N):
        r.append(h[j])
    if r == P:
        a = i
    if r == Q:
        b = i
ans = max(a-b,b-a)
print(ans)

Solution (Python):
n=int(input())
fact=[1]*13
for i in range(2,13):
	fact[i]=i*fact[i-1]
p=list(map(int,input().split()))
q=list(map(int,input().split()))
a=0
b=0
for i in range(n):
	a=a+((p[i]-1)*(fact[n-i-1]))
	b=b+((q[i]-1)*(fact[n-i-1]))
	for j in range(i+1,n):
		if(p[j]>p[i]):
			p[j]=p[j]-1
		if(q[j]>q[i]):
			q[j]=q[j]-1
print(abs(a-b))

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    p = LI()
    q = LI()
    a = 0
    b = 0
    k = 1
    for pe in permutations(range(1,n+1)):
        if list(pe) == p:
            a = k
        if list(pe) == q:
            b = k
        if a&b:
            break
        k += 1
    print(abs(a-b))
    return


if __name__ == "__main__":
    solve()