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 sys

import numpy as np
import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right
from operator import itemgetter as ig
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
INF = float("INF")
mod = 10 ** 9 + 7
"""dd = [(-1, 0), (0, 1), (1, 0), (0, -1)];
ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)];
ddn9 = ddn + [(0, 0)]
for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""

def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]  
def ws(): return sys.stdin.readline().split()
def si(): return int(sys.stdin.readline())  
def ss(): return input()
def hi(n): return [si() for _ in range(n)]
def hs(n): return [ss() for _ in range(n)]  
def s_list(): return list(input())
def mi(n): return [wi() for _ in range(n)]  
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]
def num_grid(n): return [[int(i) for i in sys.stdin.readline().split()[0]] for _ in range(n)]  
def grid(n): return [s_list() for _ in range(n)]


def main():

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

    number = []
    for i in range(1,n+1):
        number.append(i)

    perm = list(itertools.permutations(number))
    count = 0
    for L in perm:
        count += 1
        if list(L) == p:
            a = count
        if list(L) == q:
            b = count

    print(abs(a-b))

if __name__ == '__main__':
    main()

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

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

X = list(itertools.permutations(x,n))

a = 0
b = 0
for i in range(math.factorial(n)):
    if p == list(X[i]):
        a = i
    if q == list(X[i]):
        b = i

print(abs(a-b))

Solution (Python):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
ans = 0
dic = [1, 1, 2, 6, 24, 120, 720, 5040]

for i in range(N-1):
    p = sorted(P[i:])
    q = sorted(Q[i:])
    ans += (p.index(P[i])-q.index(Q[i]))*dic[N-i-1]
    
print(abs(ans))

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

def permutations(nums, t, path):
    if len(nums) == 0:
        path.append(t)
        return
    for i in range(len(nums)):
        permutations(nums[:i] + nums[i + 1:], t + [nums[i]], path)

path = []
permutations([i for i in range(1, n + 1)], [], path)
path.sort()

r = abs(path.index(p) - path.index(q))
print(r)

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

Solution (Python):
import itertools as it
N=int(input())
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
num=[i+1 for i in range(N)]
ret=list(it.permutations(num))
print(abs(ret.index(P)-ret.index(Q)))

Solution (Python):
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
nums = [i for i in range(1,n+1)]
fac = [words for words in itertools.permutations(nums)]
ans = abs(fac.index(p) - fac.index(q))
print(ans)

Solution (Python):

from itertools import permutations as permus






n = int(input())
arrP = tuple(map(int, input().split()))
arrQ = tuple(map(int, input().split()))

perms_list = list(permus(range(1,n+1)))
a = perms_list.index(arrP)
b = perms_list.index(arrQ)

ans = abs(a-b)

print(ans)

Solution (Python):
def fac(n):
    ans = 1
    for k in range(n):
         ans *= k+1
    return ans     
def order(n,p):
  count = 1
  for i in range(n):
    pi = sorted(p[i:])
    count += fac(n-i-1)*pi.index(p[i])
  return count
n = int(input())
p = list(input().split())
q = list(input().split())
print(abs(order(n,p)-order(n,q)))

Solution (Python):
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
nums = [i for i in range(1,n+1)]
fac = [words for words in itertools.permutations(nums)]
ans = abs(fac.index(p) - fac.index(q))
print(ans)

Solution (Python):
from itertools import permutations

n = int(input())
p = "".join(input().split())
q = "".join(input().split())

lst = sorted(map("".join, permutations(map(str, range(1, n+1)), n)))
print(abs(lst.index(p)-lst.index(q)))

Solution (Python):
import itertools

N = int(input())

P = input().split()
P = "".join(P)

Q = input().split()
Q = "".join(Q)

dictionary = list(itertools.permutations([str(j+1) for j in range(N)], N))
dictionary = list(map("".join, dictionary))
print(abs(dictionary.index(P)-dictionary.index(Q)))

Solution (Python):
import itertools as it
n=int(input())
q=list(map(int,input().split()))
b=list(map(int,input().split()))
List = list(it.permutations(list( range(1,n+1) )))
a=c=0
for i in range(len(List)):
    if(List[i]==tuple(q)):
        a=i
    if(List[i]==tuple(b)):
        c=i
print(abs(a-c))

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
la=[0]*n
lb=[0]*n
ans=0

for i in range(n):
  la[i]=i+1
  lb[i]=i+1


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

for i in range(n):
  sa=la.index(a[i])
  sb=lb.index(b[i])
  ans+=kaijo(n-i-1)*(sa-sb)
  la.pop(sa)
  lb.pop(sb)

print(abs(ans))

Solution (Python):
import sys
import math
import itertools

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

num_list=list(itertools.permutations(i for i in range(1,n+1)))

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

Solution (Python):
import itertools

def list_to_str(arr): 
    s = map(str, arr)
    s = ','.join(s).replace(',', '')
    return s

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


junretsu = []
for v in itertools.permutations(P, n):
    junretsu.append(list_to_str(list(v)))

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

nlist = list(itertools.permutations(i for i in range(1,n+1)))

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

Solution (Python):
import itertools

n = int(input())

p = input().replace(' ', '')
q = input().replace(' ', '')

array = []
for v in itertools.permutations(list(map(str,range(1, n+1)))):
  tmp = list(v)
  array.append(''.join(tmp))
  
array.sort()

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

Solution (Python):
import itertools

def AllPatern(n, all):
    numbers = []
    all = []
    for i in range(n):
        numbers.append(i+1)
    for i in itertools.permutations(numbers):
        all.append(list(i))

    return all


def WhichNumber(p, q, all):
    val_p = 0
    val_q = 0
    for i in range(len(all)):
        val_p += 1
        if p == all[i]:
            break
    for i in range(len(all)):
        val_q += 1
        if q == all[i]:
            break

    return val_p, val_q

def main():
    n = int(input())
    p = [int(i) for i in input().split()]
    q = [int(i) for i in input().split()]
    all = []

    all = AllPatern(n, all)
    val_p, val_q = WhichNumber(p, q, all)
    print(abs(val_p - val_q))



if __name__ == '__main__':
    main()

Solution (Python):
import itertools
N=int(input())
P,Q=[tuple(map(int,input().split())) for i in range(2)]
dictionary=sorted(itertools.permutations(P,N))
print(abs(dictionary.index(P)-dictionary.index(Q)))

Solution (Python):
import itertools
N=int(input())
P,Q=[list(map(int,input().split())) for i in range(2)]
dictionary=sorted(itertools.permutations(P,N))
print(abs(dictionary.index(tuple(P))-dictionary.index(tuple(Q))))

Solution (Python):
'''
https://atcoder.jp/contests/abc150/tasks/abc150_c
'''
def main():
    import sys
    
    sys.setrecursionlimit(10000000)
    from collections import Counter, deque
    
    from itertools import combinations, permutations
    
    from math import floor, ceil
    

    


    n = int(input())
    a = tuple(map(int, input().split()))
    b = tuple(map(int, input().split()))
    for i, x in enumerate(permutations(range(1, n+1), n)):
        if a==x:
            a = i
        if b==x:
            b = i
    print(abs(a-b))


if __name__ == '__main__':
    main()

Solution (Python):
import itertools

n = int(input())
nums = [i for i in range(1, n+1)]
p = tuple(map(int, input().split(" ")))
q = tuple(map(int, input().split(" ")))

count = 0
p_v = None
q_v = None
for i, v in enumerate(itertools.permutations(nums, n)):
    if v == p:
        count += 1
        p_v = i
    if v == q:
        count += 1
        q_v = i
    if count == 2:
        break

print(abs(q_v-p_v))

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

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

a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))
a_index=0
b_index=0

for i in range(len(l)):
    if l[i]==a:
        a_index=i+1
    elif l[i]==b:
        b_index=i+1
    else:
        continue
if a_index==0 or b_index==0:
    print(0)
else:    
    result=abs(a_index-b_index)
    print(result)

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

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

print(abs(p-q))

Solution (Python):
import itertools

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

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


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

Solution (Python):
import itertools
N=int(input())
ptuple=tuple(map(int,input().split()))
qtuple=tuple(map(int,input().split()))
permlist=list(itertools.permutations(range(1,N+1)))

pindex=0
qindex=0
for i,perm in enumerate(permlist):
  if ptuple==perm:
    pindex=i
  if qtuple==perm:
    qindex=i
    
print(abs(pindex-qindex))

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

a = [i for i in range(1, n+1)]
b = list(itertools.permutations(a, n))
c = []
for i in range(len(b)):
    c.append(list(b[i]))


ans_p = 0
ans_q = 0
for i in range(len(c)):
    if c[i] == p:
        ans_p = i+1
    if c[i] == q:
        ans_q = i+1

print(abs(ans_p-ans_q))

Solution (Python):



from fractions import gcd 
from functools import reduce
import sys
sys.setrecursionlimit(200000000)
from inspect import currentframe




def printargs2err(*args):
    names = {id(v):k for k,v in currentframe().f_back.f_locals.items()}
    print(', '.join(names.get(id(arg),'???')+' : '+repr(arg) for arg in args),file=sys.stderr)
def debug(x):
    print(x,file=sys.stderr)
def printglobals():
    for (symbol, value) in globals().items():
        print('symbol="%s"、value=%s' % (symbol, value),file=sys.stderr)
def printlocals():
    for (symbol, value) in locals().items():
        print('symbol="%s"、value=%s' % (symbol, value),file=sys.stderr)

def pin(type=int):
    return map(type,input().split())


"""
"""




        

def resolve():
    N,=pin()
    P=tuple(pin())
    Q=tuple(pin())
    
    from itertools import permutations as pm
    a=list(range(1,N+1))
    for k,item in enumerate(pm(a)):
        
        if item==P:
            p=k
            
        if item==Q:
            q=k
    print(abs(p-q))    
    

"""


"""
"""
お前カッコ閉じるの忘れてるだろ
"""
import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """3
1 3 2
3 1 2"""
        output = """3"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1"""
        output = """17517"""
        self.assertIO(input, output)
    def test_入力例_3(self):
        input = """3
1 2 3
1 2 3"""
        output = """0"""
        self.assertIO(input, output)

if __name__ == "__main__":
    resolve()

Solution (Python):
import itertools

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

lst = list(itertools.permutations(P))

a = 0
b = 0
for i in lst:
    if i <= P:
        a += 1
    if i <= Q:
        b += 1

print(abs(a-b))

Solution (Python):
import itertools

n = int(input())
p, q = [tuple(map(int, input().split())) for _ in range(2)]

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

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

Solution (Python):

n = int(input())


p, q = [list(map(int, input().split())) for _ in range(2)]


sumN = 1
pList = [0] * n
qList = [0] * n
for i in range(n):
    sumN *= i + 1
    pList[i] = i + 1
    qList[i] = i + 1

sumN = sumN // n

pSum = 0
qSum = 0

for i in range(n - 1):
    pSum += pList.index(p[i]) * sumN
    pList.pop(pList.index(p[i]))

    qSum += qList.index(q[i]) * sumN
    qList.pop(qList.index(q[i]))

    sumN = sumN // (n - i - 1)

print(abs(pSum - qSum))

Solution (Python):
import itertools

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
seq = [0] * n
a = 0
b = 0
res = 0

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

seq = list(itertools.permutations(seq))

for j in range(len(seq)):
    if list(seq[j]) == p:
        a = j + 1

    if list(seq[j]) == q:
        b = j + 1

if a > b:
    res = a - b
else:
    if a < b:
        res = b - a

print(res)

Solution (Python):
f=lambda:tuple(map(int,input().split()))
n=int(input())
tp,tq=f(),f()
import itertools as it
l=list(it.permutations(range(1,n+1)))
print(abs(l.index(tp)-l.index(tq)))

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

from itertools import permutations

order = list(range(1, n+1))
a = 0
b = 0
cnt = 0
flag = False
for i in permutations(order, n):
    if list(i) == p:
        a = cnt
    if list(i) == q:
        b = cnt
    cnt += 1

print(abs(a-b))

Solution (Python):
def main():
    from itertools import permutations
    import sys
    input=sys.stdin.readline
    n=int(input())
    p=tuple(map(int,input().split()))
    q=tuple(map(int,input().split()))
    
    cnt=1
    for i in permutations(range(1,n+1)):
        if i==p:
            pi=cnt
        if i==q:
            qi=cnt
        cnt+=1
    
    print(abs(pi-qi))
if __name__=='__main__':
    main()

Solution (Python):
import numpy as np
def fact(M):
    if M == 1:
        return 1
    else:
        return fact(M-1)*M
def count(N, X):
    number = np.arange(N)+1
    res = 1
    for i in range(N-1):
        idx = int(np.where(number == X[i])[0])
        res = res + fact(N-i-1) * idx
        number = np.delete(number,idx)
    return res

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

print(abs(count(N,P)-count(N,Q)))

Solution (Python):
import itertools

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

x = sorted(P)
xl = list(itertools.permutations(x))

tp = tuple(P)
tq = tuple(Q)

a = xl.index(tp)
b = xl.index(tq)

ans = abs(a - b)

print(ans)

Solution (Python):
import itertools

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

List = [''.join(map(str, i)) for i in itertools.permutations(range(1, n+1), n)]
List.sort()

a_ind = List.index(a)
b_ind = List.index(b)

print(abs(a_ind-b_ind))

Solution (Python):
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
fact=[1,1,2,6,24,120,720,5040]
ans=0
for i in range(n-1):
    p0,q0=sorted(p[i:]),sorted(q[i:])
    ans+=(p0.index(p[i])-q0.index(q[i]))*fact[n-i-1]
print(abs(ans))

Solution (Python):
import itertools

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
Pi = 0
Qi = 0
l = [i+1 for i in range(N)]
for i, retu in enumerate(itertools.permutations(l), 1):
    if P == retu:
        Pi = i
    if Q == retu:
        Qi = i

print(abs(Pi-Qi))

Solution (Python):
import  itertools as it

n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
cnt=[]
for i in range(1,n+1):
    cnt.append(i)
tmp=[]
for conbinations in it.permutations(cnt):
    tmp.append(list(conbinations))

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

Solution (Python):
import itertools

n = int(input())

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

x = sorted(p)

xx = list(itertools.permutations(x))

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

a = xx.index(tp)
b = xx.index(tq)

ans = abs(a - b)

print(ans)

Solution (Python):
from itertools import permutations

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

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

Solution (Python):
import itertools

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

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

Solution (Python):
import itertools

n = int(input())

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

if p == q:
    print(0)
else:
    count = 1
    for per in itertools.permutations(range(1,n+1)):
        if per == p:
            a = count
        elif per == q:
            b = count
        count += 1

    print(abs(a-b))

Solution (Python):
from itertools import permutations

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

iP = -1
iQ = -1
for idx, perm in enumerate(permutations(range(1, N+1))):
    lp = list(perm)
    if lp == P:
        iP = idx
    if lp == Q:
        iQ = idx
print(abs(iP - iQ))

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

*perm, = itertools.permutations(list(range(1, n+1)), n)
a = bisect.bisect_right(perm, p)
b = bisect.bisect_right(perm, q)

print(abs(a-b))

Solution (Python):
import math
import itertools
lis=[]
N=int(input())
P=list(map(int, input().split()))
Q=list(map(int, input().split()))
l=[i+1 for i in range(N)]
"""
lP=[i+1 for i in range(N)]
lQ=[i+1 for i in range(N)]

bangoP=[]
bangoQ=[]
pnum=0
qnum=0
for i in range(N):
    j=0
    while True:
        if (lP[j]==P[i]):
            bangoP.append(j)
            
            lP.pop(j)
            
            break
        j=j+1
for i in range(N):
    j=0
    while True:
        if (lQ[j]==Q[i]):
            bangoQ.append(j)
            
            lQ.pop(j)
            
            break
        j=j+1


for i in range(N-1):
    
    pnum=pnum+math.factorial(N-1-i)*bangoP[i]
    qnum=qnum+math.factorial(N-1-i)*bangoQ[i]
print(abs(pnum-qnum))
"""
p_list=list(itertools.permutations(l))
for i in range(len(p_list)):
    if P==list(p_list[i]):
        pnum=i
    if Q==list(p_list[i]):
        qnum=i
print(abs(pnum-qnum))

Solution (Python):
import math
lis=[]
N=int(input())
P=list(map(int, input().split()))
Q=list(map(int, input().split()))
lP=[i+1 for i in range(N)]
lQ=[i+1 for i in range(N)]

bangoP=[]
bangoQ=[]
pnum=0
qnum=0
for i in range(N):
    j=0
    while True:
        if (lP[j]==P[i]):
            bangoP.append(j)
            
            lP.pop(j)
            
            break
        j=j+1
for i in range(N):
    j=0
    while True:
        if (lQ[j]==Q[i]):
            bangoQ.append(j)
            
            lQ.pop(j)
            
            break
        j=j+1


for i in range(N-1):
    
    pnum=pnum+math.factorial(N-1-i)*bangoP[i]
    qnum=qnum+math.factorial(N-1-i)*bangoQ[i]
print(abs(pnum-qnum))

'''
wacount=0
account=0
count=0
zero=0
flag=1
cur=0
changeflag=1



 
for i in range(M):
     lis=input().split()
     
     lis[0]=int(lis[0])
     lis.append(i)
     
     s.append(lis)
 
s2=sorted(s,key=lambda x:x[0])
sorted(s2,key=lambda x:x[2])
j=1
for i in range(len(s2)):
    if s2[i][0]>j:
        j=s2[i][0]
        flag=1
        count=0
    if (s2[i][0]==j)and(flag==1):
        if s2[i][1]=="WA":
            count=count+1
        elif s2[i][1]=="AC":
            account=account+1
            wacount=wacount+count
            flag=0
            count=0
                
print(account,wacount)
s=[]
lis=[]
N,M=map(int, input().split())
wacount=0
account=0
count=0
zero=0
flag=1
cur=0
changeflag=1



 
for i in range(M):
     lis=input().split()
     
     lis[0]=int(lis[0])
     lis.append(i)
     
     s.append(lis)
 
s2=sorted(s,key=lambda x:x[0])
sorted(s2,key=lambda x:x[2])
j=1
for i in range(len(s2)):
    if s2[i][0]>j:
        j=s2[i][0]
        flag=1
        count=0
    if (s2[i][0]==j)and(flag==1):
        if s2[i][1]=="WA":
            count=count+1
        elif s2[i][1]=="AC":
            account=account+1
            wacount=wacount+count
            flag=0
            count=0
print(account,wacount)
'''

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 

def ii(): return int(sys.stdin.readline().rstrip()) 
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) 
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]

def ss(): return sys.stdin.readline().rstrip() 
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) 
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]





n=ii()

p=limss()
q=limss()

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

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

for i,j in enumerate(range(factorial(n))):

    if "".join(p)=="".join(list(map(str,arr[i]))):
        pans=j
    elif "".join(q)=="".join(list(map(str,arr[i]))):
        qans=j
    
print(abs(pans-qans))

Solution (Python):

import itertools
import sys


def solve(N: int, P: "List[int]", Q: "List[int]"):
    perm = list(itertools.permutations(range(1, N+1)))
    pi = perm.index(tuple(P))
    qi = perm.index(tuple(Q))
    ans = abs(pi - qi)
    print(ans)



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    P = [int(next(tokens)) for _ in range(N)]  
    Q = [int(next(tokens)) for _ in range(N)]  
    solve(N, P, Q)

if __name__ == '__main__':
    main()

Solution (Python):
from itertools import permutations

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

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

Solution (Python):
import itertools
n = int(input())
p = input().split()
q = input().split()
p = "".join(p)
q = "".join(q)
l = []
for i,x in enumerate(itertools.permutations(range(1,n+1))):
    l.append("".join(map(str,list(x))))
d = {}
l.sort()
for i,x in enumerate(l):
    d.update({x:i+1})
print(abs(d[p]-d[q]))

Solution (Python):
from itertools import permutations, combinations

n = int(input())
p_array = [int(x) for x in input().split()]
q_array = [int(x) for x in input().split()]
comb = sorted(permutations(p_array, n))
d = {comb[x]: x + 1 for x in range(len(comb))}
print(abs(d[tuple(p_array)]- d[tuple(q_array)]))

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

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

for i in L:
  if i == P:
    a = L.index(i)
  if i == Q:
    b = L.index(i)

print(abs(a-b))

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

L = list(itertools.permutations(range(1,N+1)))
L.sort()
for l in L:
    if l == P:
        a = L.index(l)
    if l == Q:
        b = L.index(l)
print(abs(a-b))

Solution (Python):
import itertools

def solve():
  n = int(input())
  p = list(int(i) for i in input().split())
  q = list(int(i) for i in input().split())
  
  query = [int(i) for i in range(1,n+1)]
  tp = itertools.permutations(query,n)
  i = 0
  for tb in tp:
    i += 1
    if list(tb) == p:
      a = i
    if list(tb) == q:
      b = i
  print(abs(b-a))
          
solve()

Solution (Python):


from itertools import permutations

def main():
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    pm = sorted(permutations(range(1, n + 1)))
    for i, x in enumerate(pm):
        if x == p:
            ip = i
        if x == q:
            iq = i
    print(abs(ip - iq))

if __name__ == "__main__":
    main()

Solution (Python):
import itertools
n = int(input())
p_list = list(map(int, input().split()))
q_list = list(map(int, input().split()))
p_list_perm_sorted = sorted(list(itertools.permutations(p_list)))
q_list_perm_sorted = sorted(itertools.permutations(q_list))
print(abs(p_list_perm_sorted.index(tuple(p_list)) - q_list_perm_sorted.index(tuple(q_list))))

Solution (Python):
from itertools import permutations
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
l=[]
for i in range(1,n+1):
  l.append(i)
def chk(a,b):
  for i in range(len(a)):
    if a[i]!=b[i]:
      return False
  return True
p_list=list(permutations(l))


for i in range(len(p_list)):
  if chk(p_list[i],p):
    a=i
  if chk(p_list[i],q):
    b=i
print(abs(a-b))

Solution (Python):
import math
from functools import reduce
from collections import deque
import itertools
import sys
sys.setrecursionlimit(10**7)


def get_nums_l():
    return [ int(s) for s in input().split(" ")]


def get_nums_n(n):
    return [ int(input()) for _ in range(n)]


def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

n = int(input())
p = input()
q = input()

p_count = 1
q_count = 1

def kaijo(n):
    ret = 1
    for i in range(n):
        ret *= n
    return ret

for rrr in itertools.permutations(map(str,range(1,n+1))):
    s = " ".join(rrr)
    if s < p:
        p_count += 1
    if s < q:
        q_count += 1


print(abs(p_count - q_count))

Solution (Python):
from itertools import permutations

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

perms = list(permutations(range(1, n + 1)))
a = perms.index(p)
b = perms.index(q)

print(abs(a - b))

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip()
input_nums = lambda: list(map(int, input().split()))

import itertools

N = int(input())
P = tuple(input_nums())
Q = tuple(input_nums())

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

index_P = all.index(P)
index_Q = all.index(Q)
print(abs(index_P - index_Q))

Solution (Python):
from bisect import bisect_left

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

def fact(n):
    num = 1
    for i in range(1, n+1):
        num *= i
    return num


def order(N, P):
    order = 0
    L = [i for i in range(1, N + 1)]
    """
    下からN桁目が一定なグループは(N-1)!個
    下から(N-1)桁目が一定なグループは(N-2)!個
    ...
    下からi桁目(1 <= i <= N)が一定なグループは(i-1)!個
    ...
    下から1桁目が一定なグループは0!個
    """
    for i in range(N):
        order += bisect_left(L, P[i]) * fact(N - i - 1)
        L.remove(P[i])
        
    return order + 1

print(abs(order(N, P) - order(N, Q)))

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

from itertools import permutations

lst = list(permutations(range(1,n+1)))
lst.sort()
print(abs(lst.index(P) - lst.index(Q)))

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read 
input = sys.stdin.buffer.readline
def inputS(): return input().rstrip().decode()
readlines = sys.stdin.buffer.readlines 

from itertools import permutations

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

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