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

Solution (Python):
from itertools import permutations

N = int(input())
Ps = tuple(map(int,input().split()))
Qs = tuple(map(int,input().split()))

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

a = 0
b = 0
for i in range(len(patterns)):
    if Ps == patterns[i]:
        a = i
    if Qs == patterns[i]:
        b = i

print(abs(a-b))

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

def factorial(num):
    if num == 1:
        return 1
    return num * factorial(num - 1)

def count_order(group):
    numbers = [i for i in range(1, N + 1)]
    res = 1
    for i in range(len(group) - 1):
        num = group[i]
        res += numbers.index(num) * pattern[-(i + 1)]
        numbers.pop(numbers.index(num))
    return res


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

pattern = [factorial(i) for i in range(1, N)]
res_p = count_order(P)
res_q = count_order(Q)

print(abs(res_p - res_q))

Solution (Python):





from itertools import permutations


def solv(N, P, Q):
    if P > Q:
        P, Q = Q, P
    for idx, l in enumerate(permutations(range(1, N+1))):
        if P == l:
            start = idx
        if Q == l:
            return idx - start


if __name__ == "__main__":

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

    ans = solv(N, P, Q)

    print(ans)

Solution (Python):
"""
author : halo2halo
date : 4, Feb, 2020
"""

import sys
import itertools





read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
INF = 10 ** 9

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

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

Solution (Python):
from itertools import permutations
n=int(input())
def f(A):
    LL=permutations(range(n))
    for i,L in enumerate(LL):
        if A==L:
            return i
P=tuple(map(lambda x: int(x)-1,input().split()))
Q=tuple(map(lambda x: int(x)-1,input().split()))
print(abs(f(P)-f(Q)))

Solution (Python):
from itertools import permutations

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

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

l = []
for v in permutations(arr,n):
    v = list(v)
    v = list(map(str,v))
    l.append(''.join(v))

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

print(abs(a-b))

Solution (Python):
import math

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

def f(x):
  y = 1
  z = []
  for i in range(len(x)):
    y += (int(x[i])-len(list(filter(lambda k:k<int(x[i]),z)))-1)*math.factorial(n-i-1)
    z.append(int(x[i]))
  return y

print(abs(f(p)-f(q)))

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

def stri(n):
    a = 1
    for i in range(n):
        a *= i+1
    return a

def cou(lis):
    tlis = sorted(lis)
    r = 0
    for n in lis:
        r += stri(len(tlis)-1)*(tlis.index(n)-1)
        tlis.remove(n)
    return r



print(abs(cou(P)-cou(Q)))

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

Solution (Python):
from itertools import permutations

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

array = [int(i) for i in range(1, n+1)]
c = 1
n_p = 0
n_q = 0

for perm in permutations(array):
    if perm == p:
        n_p = c
        
    if perm == q:
        n_q = c
        
    c += 1
    
print(abs(n_p - n_q))

Solution (Python):
from itertools import accumulate, product, permutations, combinations

N = int(input())
l = [i+1 for i in range(N)]
c_list = list(permutations(l))
P = tuple(int(_) for _ in input().split())
Q = tuple(int(_) for _ in input().split())
P_value = 0
Q_value = 0
for index, item in enumerate(c_list):
    if P == item:
        P_value = index+1
    if Q == item:
        Q_value = index+1

print(abs(P_value - Q_value))

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

left = 0
r = 0
gen = [x for x in range(1, N+1)]
i = 1
for perm in permutations(gen):
    if perm == P:
        left = i

    if perm == Q:
        r = i
    i += 1

print(abs(left-r))

Solution (Python):
import itertools
n=int(input())
a="".join(list(input().split()))
b="".join(list(input().split()))
l=itertools.permutations(map(str,range(1,n+1)))
ans=0
for i,j in enumerate(l):
  if a=="".join(list(j)):
    ans+=i
  if b=="".join(list(j)):
    ans-=i
print(abs(ans))

Solution (Python):
N=int(input())
import itertools
import bisect
L=list(i for i in range(1,N+1))
L1=[]
S1=tuple(map(int,input().split()))
S2=tuple(map(int,input().split()))
for v in itertools.permutations(L,N):
    L1.append(v)
print(abs(bisect.bisect(L1,S1)-bisect.bisect(L1,S2)))

Solution (Python):
import numpy as np
import math

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

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


def banme(a):
    num = [i+1 for i in range(n)]
    now = 1
    for i in range(n):
        now += num.index(a[i])*f[n-i-1]
        num.remove(a[i])
    return now

print(int(math.fabs(banme(p)-banme(q))))

Solution (Python):



from math import factorial
import numpy

def calc_index(xs, n):
  remaining = numpy.ones(n)
  index = 0
  for i, x in enumerate(xs):
    remaining[x-1] = 0
    index += numpy.sum(remaining[:(x-1)]) * factorial(n-(i+1))
  return int(index)


def main():
  n = int(input())
  Ps = list(map(int, input().strip().split()))
  Qs = list(map(int, input().strip().split()))
  print(abs(calc_index(Ps, n) - calc_index(Qs, n)))

if __name__=='__main__':
  main()

Solution (Python):
import itertools
n = int(input())
L = tuple((map(int,input().split())))
M = tuple(map(int,input().split()))
a = 0
b = 0
K = [i for i in range(1,n+1)]
PER = list(itertools.permutations(K))
for i in range(len(PER)):
  if PER[i] == L:
    a = i
  if PER[i] == M:
    b = i
print(abs(a-b))

Solution (Python):
import itertools

N = int(input())
P = tuple(input().split())
Q = tuple(input().split())
permutations = list(itertools.permutations(map(str, range(1, N+1))))

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

print(ans)

Solution (Python):
import itertools

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

pp = list(itertools.permutations(p))
qq = list(itertools.permutations(q))

pp.sort()
qq.sort()

a = 0
b = 0

for i in range(len(pp)):
    if pp[i] == tuple(p):
        a = i + 1

for i in range(len(qq)):
    if pp[i] == tuple(q):
        b = i + 1

print(abs(a - b))

Solution (Python):

import itertools
N = int(input())
P = input().split(" ")
Q = input().split(" ")
perm = itertools.permutations(P, len(P))
a = b = 0
for i in perm:
    if int("".join(P)) >= int("".join(i)):
        a += 1
    if int("".join(Q)) >= int("".join(i)):
        b += 1
print(abs(a-b))

Solution (Python):

import itertools
N = int(input())
P = input().split(" ")
Q = input().split(" ")
perm = itertools.permutations(P, len(P))
a = b = 0
for i in perm:
    if int("".join(P)) >= int("".join(i)):
        a += 1
    if int("".join(Q)) >= int("".join(i)):
        b += 1
print(abs(a-b))

Solution (Python):

import math

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

def sorted_index(x, nums):
    sorted_nums = sorted(nums)
    ans = sorted_nums.index(x)
    return ans


def dict_index(num):
    ans=0
    for i in range(n-1):
        x = num[i]
        idx = sorted_index(x, num[i:])
        ans += (math.factorial(n-i-1)*idx)
    return ans

ansp = dict_index(p)
ansq=dict_index(q)
print(abs(ansp-ansq))

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

import math


def get_rank(x, n):
    rank = 0
    for i in range(n):
        head_x = x[i]
        x_list = list(x[i:])
        ways = math.factorial(len(x_list))
        sorted_x_list = sorted(x_list)
        number = sorted_x_list.index(head_x)
        rank += (ways/len(x_list))*number
    return int(rank)


print(abs(get_rank(p, n) - get_rank(q, n)))

Solution (Python):
import itertools
n = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
p_list = list(itertools.permutations(P, n))
p_list = sorted(p_list)

for i in range(len(p_list)):
    if p_list[i] == tuple(P):
        pnum = i

    if p_list[i] == tuple(Q):
        qnum = i

print(abs(pnum-qnum))

Solution (Python):
import itertools

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





p_index = 0
q_index = 0



for i, s in enumerate(itertools.permutations(range(1,N+1))):
    
    if P == s:
        p_index = i
    if Q == s:
        q_index = i

print(abs(p_index-q_index))

Solution (Python):
import itertools

n = ''
for i in range(1,int(input())+1):
    n += str(i)
p = tuple(x for x in input().split())
q = tuple(x for x in input().split())

ans = list(itertools.permutations(n))

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

Solution (Python):
import itertools
n = int(input())
p=tuple(map(int ,input().split()))
q=tuple(map(int ,input().split()))
i = list(itertools.permutations(p))
i.sort()
print(abs((i.index(p)+1)-(i.index(q)+1)))

Solution (Python):
import itertools

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

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

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
P = LIST()
Q = LIST()

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

per = permutations(a)

index = 1
for i in per:
	if list(i) == P:
		a = index
	if list(i) == Q:
		b = index
	index += 1

print(abs(a-b))

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

def idid(x):
  c = [i+1 for i in range(n)]
  ans = 0
  div = 1
  for i in range(n):
    div *= i+1
  for i in range(n):
    div //= n-i
    for j in range(len(c)):
      if x[i] == c[j]:
        del c[j]
        ans += j * div
        break
  return ans
print(abs(idid(a)-idid(b)))

Solution (Python):
import itertools

n = int(input())
p = input().replace(" ", "")
q = input().replace(" ", "")
m = ""
for i in range(1, n + 1):
    m += str(i)
anagram_list = ["".join(v) for v in itertools.permutations(m)]

pa = 0
qa = 0

for i in range(len(anagram_list)):
    if anagram_list[i] == p:
        pa = i+1
    if anagram_list[i] == q:
        qa = i+1
print(abs(pa-qa))

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

Solution (Python):
def main():
    N = int(input())
    p = input().strip().replace(" ", "")
    q = input().strip().replace(" ", "")

    import itertools
    l = ["".join(map(str, s)) for s in itertools.permutations(range(1, N+1))]
    i = l.index(p)
    j = l.index(q)
    print(abs(i-j))


if __name__ == '__main__':
    main()

Solution (Python):
from itertools import permutations
n = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
PD=[]
for v in permutations(P):
    PD.append(list(v))
a = sorted(PD).index(P)
QD = []
for x in permutations(Q):
    QD.append(list(x))
b = sorted(QD).index(Q)
print(abs(a-b))

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

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

n_list = [x for x in range(1, n+1)]

a = b = 0
for n, i in enumerate(permutations(n_list, n)):
  
  if i == P:
    a = n
  if i == Q:
    b = n
    
print(abs(a-b))

Solution (Python):
import itertools

def is_same(A, B):
    for a, b in zip(A, B):
        if a != b:
            return False
    return True

def main():
    N = int(input())

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

    p = 0
    q = 0
    D = list(itertools.permutations(range(1, N+1)))
    for i, d in enumerate(D):
        if is_same(d, P):
            p = i
        if is_same(d, Q):
            q = i
    print(abs(p-q))

if __name__ == '__main__':
    main()

Solution (Python):
import sys,collections as cl,bisect as bs,itertools as it
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): 
    return list(map(int,input().split()))
def m(): 
    return map(int,input().split())
def onem(): 
    return int(input())
def s(x): 
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): 
    return " ".join(map(str,x))
def max2(x): 
    return max(map(max,x))
def In(x,a): 
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""



n = onem()

a = tuple(input().split())
b = tuple(input().split())

aa = sorted(a)

po = list(it.permutations(aa))

coa = 0
cob = 0
for i in range(len(po)):
    if a == po[i]:
        coa = i
    if b == po[i]:
        cob = i
print(abs(coa-cob))

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

count = 0
p = -1
q = -1

A = [0 for _ in range(n)]
def calc(i):
    global p, q, count
    if p != -1 and q != -1:
        return
    if i == n:
        count += 1
        if A == P:
            p = count
        if A == Q:
            q = count
        return
    for j in range(1, n+1):
        A[i] = j
        flag = 0
        for k in range(i):
            if A[k] == j:
                flag = 1
        if flag == 0:
            calc(i + 1)

calc(0)
print(abs(p - q))

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

count = 0
p = -1
q = -1

A = [0 for _ in range(n)]
def calc(i):
    global p, q, count
    if p != -1 and q != -1:
        return
    if i == n:
        count += 1
        if A == P:
            p = count
        if A == Q:
            q = count
        return
    for j in range(1, n+1):
        A[i] = j
        flag = 0
        for k in range(i):
            if A[k] == j:
                flag = 1
        if flag == 0:
            calc(i + 1)

calc(0)
print(abs(p - q))

Solution (Python):

import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def roundUp(a, b):
        return -(-a // b)

    @staticmethod
    def toUpperMultiple(a, x):
        return Math.roundUp(a, x) * x

    @staticmethod
    def toLowerMultiple(a, x):
        return (a // x) * x

    @staticmethod
    def nearPow2(n):
        if n <= 0:
            return 0
        if n & (n - 1) == 0:
            return n
        ret = 1
        while(n > 0):
            ret <<= 1
            n >>= 1
        return ret

    @staticmethod
    def sign(n):
        if n == 0:
            return 0
        if n < 0:
            return -1
        return 1

    @staticmethod
    def isPrime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


class PriorityQueue:
    def __init__(self, l=[]):
        self.__q = l
        heapq.heapify(self.__q)
        return

    def push(self, n):
        heapq.heappush(self.__q, n)
        return

    def pop(self):
        return heapq.heappop(self.__q)


MOD = int(1e09) + 7
INF = int(1e15)


def main():
    
    N = Scanner.int()
    P = Scanner.map_int()
    Q = Scanner.map_int()
    A = [i for i in range(1, N+1)]
    p, q = 0, 0
    for i, v in enumerate(itertools.permutations(A, N)):
        if list(v) == P:
            p = i
        if list(v) == Q:
            q = i
    print(abs(q-p))
    return


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()))
ans = 0


set_ = set()
for n in range(1,N+1):
  set_.add(n)
perm = list(permutations(set_))


idx_p = 0
idx_q = 0
idx = 0
for p in perm:
  if p == P:
    idx_p = idx
  if p == Q:
    idx_q = idx
  idx += 1
  
ans = abs(idx_p-idx_q)
print(ans)

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

from itertools import permutations

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


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

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

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

from itertools import permutations
perms = list(permutations(range(1, N+1), N))

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

Solution (Python):
def solve(n, P, Q):
    facts = [1] * n
    for i in range(2, n):
        facts[i] = facts[i - 1] * i

    def count_order(X):
        cands = [True] * n
        num = 0
        for i, x in enumerate(X):
            num += sum(cands[:x - 1]) * facts[n - i - 1]
            cands[x - 1] = False
        return num

    return abs(count_order(P) - count_order(Q))

_n = int(input())
_P = list(map(int, input().split()))
_Q = list(map(int, input().split()))
print(solve(_n, _P, _Q))

Solution (Python):
def solve(n, P, Q):
    facts = [1] * n
    for i in range(2, n):
        facts[i] = facts[i - 1] * i

    def count_order(X):
        cands = [True] * n
        num = 0
        for i, x in enumerate(X):
            num += sum(cands[:x - 1]) * facts[n - i - 1]
            cands[x - 1] = False
        return num

    return abs(count_order(P) - count_order(Q))

_n = int(input())
_P = list(map(int, input().split()))
_Q = list(map(int, input().split()))
print(solve(_n, _P, _Q))

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

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


def kai(i):
    ret = 1
    while i > 0:
        ret *= i
        i -= 1
        
    return ret


def count(l):
    n = len(l)
    i = 0

    ans = 0
    while i < n:
        kake = kai(n - i - 1)
        ans += (l[i] - 1) * kake
        now = l[i]
        for num in range(len(l)):
            if l[num] > now:
                l[num] -= 1
            
        i += 1
    
    return ans


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

Solution (Python):
from itertools import permutations

N = int(input())
P = input().split()
Q = input().split()
  
L = list(permutations("".join(list(map(str,list(range(1,N+1))))), N))

idx = 0
for l in L:
  
  if P == list(l):
    a = idx
  if Q == list(l):
    b = idx
  idx += 1
  
print(abs(b-a))

Solution (Python):
from itertools import permutations

N = int(input())
P = input().split()
Q = input().split()
  
L = list(permutations("".join(list(map(str,list(range(1,N+1))))), N))

idx = 0
for l in L:
  
  if P == list(l):
    a = idx
  if Q == list(l):
    b = idx
  idx += 1
  
print(abs(b-a))

Solution (Python):
from itertools import permutations
N=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
s=0
for x in permutations(range(1,N+1)):
    s=s+1
    if list(x)==p:
        a=s
    if list(x)==q:
        b=s
print(abs(a-b))

Solution (Python):
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
l = []
for i in range(1, n+1):
    l.append(i)
ll = list(itertools.permutations(l))
for i in range(len(ll)):
    if ll[i] == p:
        pre = i
    if ll[i] == q:
        pos = i
print(abs(pre-pos))

Solution (Python):
import itertools

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

seq = sorted(P)

p_num = None
q_num = None

def is_same(pq, l):
    for i in range(len(pq)):
        if pq[i] != l[i]:
            return False
    return True

for index, l in enumerate(list(itertools.permutations(seq))):
    if is_same(P, l):
        p_num = index + 1
    if is_same(Q, l):
        q_num = index + 1
    if p_num is not None and q_num is not None:
        print(abs(p_num - q_num))
        exit(0)

Solution (Python):

import re
import math
import itertools
from copy import deepcopy
import fractions
import random
from heapq import heappop,heappush
import time
import sys
readline = sys.stdin.readline

alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def bin_(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def fac_list(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:
        return num
def get_primes(n,type="int"):
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=2):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def join(A,c=" "):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s

n=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
A=[a for a in range(1,n+1)]
B=list(itertools.permutations(A))
ans=0
for a in range(len(B)):
    B[a]=list(B[a])
    if B[a]==P:
        ans+=a+1
    if B[a]==Q:
        ans-=a+1
print(abs(ans))

Solution (Python):
from sys import stdin
f_i = stdin

N = int(f_i.readline())
P = ''.join(f_i.readline().split())
Q = ''.join(f_i.readline().split())

from itertools import permutations
seq = permutations(str(i) for i in range(1, N + 1))
seq = sorted(''.join(p) for p in seq)

from bisect import bisect_left
idx1 = bisect_left(seq, P)
idx2 = bisect_left(seq, Q)

print(abs(idx1 - idx2))

Solution (Python):
import itertools
n = int(input())
p =[int(i) for i in input().split()]
q =[int(i) for i in input().split()]
a = 0
b = 0
cnt = 0
p1= p.copy()
p1.sort()
n_list = list(itertools.permutations(p1))
for i in n_list:
    if list(i)==p:
        a = cnt +1
    if list(i)==q:
        b = cnt +1
    cnt += 1
        
print(abs(a-b))

Solution (Python):
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
from itertools import permutations
l = list(range(1, n + 1))
np = 0
for x in permutations(l, n):
    np += 1
    if p == list(x): break
l = list(range(1, n + 1))
nq = 0
for x in permutations(l, n):
    nq += 1
    if q == list(x): break
print(abs(nq - np))

Solution (Python):


import itertools


def main():
    N = int(input())
    P = tuple(map(int, input().split()))
    Q = tuple(map(int, input().split()))
    result = 0
    seq = [i + 1 for i in range(N)]
    seq_list = list(itertools.permutations(seq, N))
    print(abs(seq_list.index(P) - seq_list.index(Q)))


if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque
n = int(input())
p_que = deque(map(int, input().split()))
q_que = deque(map(int, input().split()))

que = deque(i for i in range(1, n+1))
cnt = 0
a = 0
b = 0

def dfs(d, q):
  
  
  for i in list(q):
    
    d.append(i)
    q.remove(i)
    
    if q == deque([]):
      global cnt
      cnt += 1
      
      if d == p_que:
        global a
        a = cnt
      if d == q_que:
        global b
        b = cnt
      
      d.remove(i)
      q.appendleft(i)
      return
    
    dfs(d, q)
    
    
    d.remove(i)
    if i > q[0]:
      q.append(i)
    else:
      q.appendleft(i)
    q = deque(sorted(q))

dfs(deque(), que)

print(abs(a-b))

Solution (Python):
def fact(n):
  ret=1
  for i in range(2,n+1):
    ret=ret*i
  return ret

n=int(input())
arr1=list(map(int,input().split()))
arr2=list(map(int,input().split()))
cnt1=0
cnt2=0
checked1=[0]*(n+1)
checked2=[0]*(n+1)
for i in range(n):
  checked1[arr1[i]]=1
  checked2[arr2[i]]=1
  cnt1+=(arr1[i]-1-sum(checked1[:arr1[i]]))*fact(n-i-1)
  cnt2+=(arr2[i]-1-sum(checked2[:arr2[i]]))*fact(n-i-1)
print(abs(cnt1-cnt2))

Solution (Python):
def fact(n):
  ret=1
  for i in range(2,n+1):
    ret=ret*i
  return ret

n=int(input())
arr1=list(map(int,input().split()))
arr2=list(map(int,input().split()))
cnt1=0
cnt2=0
checked1=[0]*(n+1)
checked2=[0]*(n+1)
for i in range(n):
  checked1[arr1[i]]=1
  checked2[arr2[i]]=1
  cnt1+=(arr1[i]-1-sum(checked1[:arr1[i]]))*fact(n-i-1)
  cnt2+=(arr2[i]-1-sum(checked2[:arr2[i]]))*fact(n-i-1)
print(abs(cnt1-cnt2))

Solution (Python):
def fact(n):
  ret=1
  for i in range(2,n+1):
    ret=ret*i
  return ret

n=int(input())
arr1=list(map(int,input().split()))
arr2=list(map(int,input().split()))
cnt1=0
cnt2=0
checked1=[0]*(n+1)
checked2=[0]*(n+1)
for i in range(n):
  checked1[arr1[i]]=1
  checked2[arr2[i]]=1
  cnt1+=(arr1[i]-1-sum(checked1[:arr1[i]]))*fact(n-i-1)
  cnt2+=(arr2[i]-1-sum(checked2[:arr2[i]]))*fact(n-i-1)
print(abs(cnt1-cnt2))

Solution (Python):
def fact(n):
  ret=1
  for i in range(2,n+1):
    ret=ret*i
  return ret

n=int(input())
arr1=list(map(int,input().split()))
arr2=list(map(int,input().split()))
cnt1=0
cnt2=0
checked1=[0]*(n+1)
checked2=[0]*(n+1)
for i in range(n):
  checked1[arr1[i]]=1
  checked2[arr2[i]]=1
  cnt1+=(arr1[i]-1-sum(checked1[:arr1[i]]))*fact(n-i-1)
  cnt2+=(arr2[i]-1-sum(checked2[:arr2[i]]))*fact(n-i-1)
print(abs(cnt1-cnt2))

Solution (Python):
import itertools
n=int(input())
p=tuple(map(int,input().split()))
q=tuple(map(int,input().split()))
arrs=list(itertools.permutations(range(1,n+1)))
cnt1=0
cnt2=0
for i in range(len(arrs)):
  if arrs[i]==p:
    cnt1=i
  if arrs[i]==q:
    cnt2=i
print(abs(cnt2-cnt1))

Solution (Python):
from itertools import permutations
n = int(input())
a = list(map(int,input().split()))
a = tuple(map(lambda x: x-1, a))
b = list(map(int,input().split()))
b = tuple(map(lambda x: x-1, b))
ai = 0
bi = 0
ind = 0
for i in permutations(range(n),n):

    if i == a: ai = ind
    if i == b: bi = ind
    ind += 1
print(abs(ai-bi))

Solution (Python):
import math

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

p=0
q=0

for i in range(N):
  n = P[i]-1
  
  for j in range(i):
    if P[j]<P[i]:
      n -= 1
  
  p += n*math.factorial(N-(i+1))

for i in range(N):
  n = Q[i]-1
  
  for j in range(i):
    if Q[j]<Q[i]:
      n -= 1
  
  q += n*math.factorial(N-(i+1))

print(abs(p-q))

Solution (Python):
import itertools
n = int(input())
ps = tuple(input().split())
qs = tuple(input().split())

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


print(abs(s_list.index(ps) - s_list.index(qs)))

Solution (Python):
n = int(input())
ps = tuple(map(int, input().split()))
qs = tuple(map(int, input().split()))

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

arr2 = list(itertools.permutations(arr))

nump = arr2.index(ps)
numq = arr2.index(qs)

print(max(nump, numq) - min(nump,numq))