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 math
import os
import itertools
import string
import heapq
import bisect
import re
import queue
from collections import Counter
from collections import defaultdict
from functools import lru_cache


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

    @staticmethod
    def float():
        return float(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 map_float():
        return [float(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 PI():
        return math.acos(-1)

    @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

    @staticmethod
    def divisor(n):
        i = 1
        table = []
        while i * i <= n:
            if n % i == 0:
                table.append(i)
                table.append(n // i)
            i += 1
        table = list(set(table))
        return table


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)

    def list(self):
        return self.__q

    def length(self):
        return len(self.__q)


sys.setrecursionlimit(1000000)
MOD = int(1e09) + 7
INF = int(1e30)


def main():
    
    N = Scanner.int()
    P = tuple(Scanner.map_int())
    Q = tuple(Scanner.map_int())
    perm = list(itertools.permutations([i + 1 for i in range(N)]))
    print(abs(perm.index(P) - perm.index(Q)))
    return


if __name__ == "__main__":
    main()

Solution (Python):
from itertools import permutations

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

p_order = q_order = cnt = 0
for d in permutations(range(1, n+1)):
    cnt += 1
    if not p_order:
        if list(d) == p:
            p_order = cnt
    if not q_order:
        if list(d) == q:
            q_order = cnt
    if p_order and q_order:
        break

print(abs(p_order - q_order))

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

for i in range(len(ll)): 
    if list(ll[i])==p: 
        a=i 
    if list(ll[i])==q: 
        b=i 
print(abs(a-b))

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

import itertools

ptn = list(itertools.permutations(range(1, n + 1)))
a = ptn.index(p)
b = ptn.index(q)
ans = abs(a - b)

print(ans)

Solution (Python):


n = int(input().rstrip())


def get_list(flag: int):
    if (1 << n) - 1 == flag:
        return []
    ret = []
    for i in range(n):
        key = (1 << i)
        if (flag & key) != 0:
            continue
        tmp = get_list(flag + key)
        if len(tmp) == 0:
            ret.append([i + 1])
        else:
            for t in tmp:
                ret.append([i + 1] + t)
    return ret


list1 = [int(i) for i in input().rstrip().split(" ")]
list2 = [int(i) for i in input().rstrip().split(" ")]

index1 = 0
index2 = 0

kumiawase = get_list(0)
for i in range(len(kumiawase)):
    if list1 == kumiawase[i]:
        index1 = i
    if list2 == kumiawase[i]:
        index2 = i

print(abs(index1 - index2))

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

Solution (Python):







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

    fullbit = (1 << N) - 1

    def full(ary, val, bit, ret):
        if bit == fullbit:
            ret.append(val)
            return
        for i in range(N):
            if bit & (1 << i) == 0:
                full(ary, val * 10 + ary[i], bit | (1 << i), ret)

    def to_i(ary):
        n = 0
        for v in ary:
            n = n * 10 + v
        return n

    def index_of(ary, val):
        lower = 0
        upper = len(ary) - 1
        while lower <= upper:
            mid = lower + (upper - lower) // 2
            v = ary[mid]
            if v < val:
                lower = mid + 1
            elif v > val:
                upper = mid - 1
            else:
                return mid

        return lower

    ret1 = []
    full(P, 0, 0, ret1)
    ret1.sort()
    a = index_of(ret1, to_i(P))

    ret2 = []
    full(Q, 0, 0, ret2)
    ret2.sort()
    b = index_of(ret2, to_i(Q))

    print(abs(a - b))


main()

Solution (Python):
import itertools

n=int(input())
p=[int(x) for x in input().split()]
q=[int(x) for x in input().split()]
dic={}
cnt=0
a=0
b=0
for i in itertools.permutations(range(1,n+1)):
    dic[cnt]=i
    if list(i) == p:
        a=cnt
    if list(i) == q:
        b=cnt
    cnt+=1
print(abs(a-b))

Solution (Python):
import sys
import math
import fractions
import itertools
from collections import deque
import copy
import bisect

MOD = 10 ** 9 + 7
INF = 10 ** 18 + 7
input = lambda: sys.stdin.readline().strip()

N = int(input())
L = list(itertools.permutations(list(range(1, N + 1)), N))
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
for num, i in enumerate(L):
    if i == P:
        a = num
    if i == Q:
        b = num
print(abs(a - b))

Solution (Python):
import itertools


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

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

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

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

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

Solution (Python):
from itertools import permutations
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
A = []
for z in permutations(range(1,N+1),N):
    A.append(z)
A = sorted(A)
indP = -1
indQ = -1
for i,a in enumerate(A):
    if a==P:
        indP = i
    if a==Q:
        indQ = i
print(abs(indP-indQ))

Solution (Python):
import itertools

n=int(input())
p=''.join(list(map(str,input().split())))
q=''.join(list(map(str,input().split())))
arr=[]
for pairs in itertools.permutations([str(i) for i in range(1,n+1)]):
  arr.append(''.join(list(pairs)))
arr=sorted(arr)
print(abs(arr.index(q)-arr.index(p)))

Solution (Python):
from itertools import permutations

n = int(input())
a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))
x, y = 0, 0
perm = list(permutations(list(range(1, n+1))))

for i in perm:
    if i == a:
        x = perm.index(i)
    if i == b:
        y = perm.index(i)
print(abs(x-y))

Solution (Python):
import math
n=int(input())
s=list(map(int,input().split()))
t=list(map(int,input().split()))
lists=[]
listt=[]
sums=0
sumt=0

def rank(n,l):
  for i in range(len(l)):
    if n==l[i]:
      l.remove(l[i])
      return i+1
    
for i in range(n):
  lists.append(i+1)
  listt.append(i+1)
for i in range(n):
  sums+=(rank(s[i],lists)-1)*(math.factorial(n-1-i))
  sumt+=(rank(t[i],listt)-1)*(math.factorial(n-1-i))
if sums<sumt:
  tmp=sums
  sums=sumt
  sumt=tmp
print(sums-sumt)

Solution (Python):
import itertools

if __name__ == '__main__':

	n = int(input())

	A = tuple(map(int,input().split()))
	B = tuple(map(int,input().split()))

	C  = [i for i in range(1,n+1)]
	D = [v for v in itertools.permutations(C, n)]

	a = D.index(A)
	b = D.index(B)

	print(abs(a-b))

Solution (Python):
from collections import deque

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
a, b, x = 0, 0, 1
c = deque()
d = deque()
for i in range(n):
    c.append(i + 1)
    d.append(i + 1)
    x *= i + 1
for i in range(n):
    for j in range(n - i):
        if p[i] == c[j]:
            a += j * x / (n - i)
            c.remove(p[i])
            break
    for j in range(n - i):
        if q[i] == d[j]:
            b += j * x / (n - i)
            d.remove(q[i])
            break
    x /= n - i

print(abs(int(a - b)))

Solution (Python):
from itertools import permutations as perm
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
x = [int(x) for x in range(1,n+1)]
lis = list(perm(x,n))

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

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

lis = [i for i in range(1, N+1)]
a = 0
b = 0
ans = list(itertools.permutations(lis))
TP=tuple(P)
TQ=tuple(Q)
for n, i in enumerate(ans):
    if(i == TP):
        a=n+1
        if(b!=0):
            break
    if(i==TQ):
        b=n+1
        if(a!=0):
            break

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()))
p = 0
q = 0
for idx, t in enumerate(permutations(range(1, N + 1))):
    if t == P:
        p = idx + 1
    if t == Q:
        q = idx + 1
    if p and q:
        break
print(abs(p - q))

Solution (Python):
import itertools

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

tmp = [i for i in range(1,N+1)]
nums = []
for i in itertools.permutations(tmp):
    _ = []
    for j in i:
        _.append(str(j))
    nums.append("".join(_))

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

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

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

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

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

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

t = [0]*8
t[1] = 1
for i in range(2,n):
  t[i] = i * t[i - 1]

a = 0
l = list(range(1, n+1))
for i in range(n):
  a += l.index(p[i]) * t[len(l) - 1]
  l.remove(p[i])

b = 0
l = list(range(1, n+1))
for i in range(n):
  b += l.index(q[i]) * t[len(l) - 1]
  l.remove(q[i])

print(abs(a - b))

Solution (Python):
def ABC106_B():
    def make_divisors(n):
        divisors = []
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                divisors.append(i)
                if i != n // i:
                    divisors.append(n // i)
        
        return divisors
    N = I()
    ans = 0
    for i in range((N+1)//2):
        cur = i*2+1
        if len(make_divisors(cur))==8:
            ans += 1
    print(ans)
    return

def ABC122_B():
    S = SI()
    ans = 0
    cur = 0
    d = {"A","C","G","T"}
    for s in S:
        if s in d:
            cur += 1
        else:
            ans = max(ans,cur)
            cur = 0
    ans = max(ans,cur)
    print(ans)
    return

def paken2019_C():
    N, M = LI()
    A = [LI()for _ in range(N)]
    T = [i for i in range(M)]
    ans = 0
    for t1,t2 in itertools.permutations(T,2):
        cur = 0
        for i in range(N):
            cur += max(A[i][t1],A[i][t2])
        ans = max(ans,cur)
    print(ans)
    return

def ABC95_C():
    A, B, C, X, Y = LI()
    if A+B<=C*2:
        ans = A*X+B*Y
    else:
        if X>Y:
            ans = Y*C*2 + min(A,C*2)*(X-Y)
        else:
            ans = X*C*2 + min(B,C*2)*(Y-X)
    print(ans)
    return

def SMTB_D():
    def flag(n,s):
        for l in range(n,N):
            if S[l]==str(s):
                return l
        return N
    N = I()
    S = SI()
    ans = 0
    for i in range(10):
        L1 = flag(0,i)
        for j in range(10):
            L2 = flag(L1+1,j)
            for k in range(10):
                L3 = flag(L2+1,k)
                if L3<N:
                    ans += 1
                    
    print(ans)
    return

def JOI2007_3():
    N = I()
    V = [LI() for _ in range(N)]
    D = set()
    for vx,vy in V:
        D.add((vx,vy))
    ans = 0
    for i in range(N):
        a1, b1 = V[i]
        for j in range(i+1,N):
            a2, b2 = V[j]
            va, vb = a2 - a1, b2 - b1
            if (a1 + vb, b1 - va) in D and (a2 + vb, b2 - va) in D:
                ans = max(ans, va ** 2 + vb ** 2)
            if (a1 - vb, b1 + va) in D and (a2 - vb, b2 + va) in D:
                ans = max(ans, va ** 2 + vb ** 2)
    print(ans)
    return
"""
10
9 4
4 3
1 1
4 2
2 4
5 8
4 0
5 3
0 5
5 2
"""

def square869120Contest():
    def length(a,b,x,y):
        if x>y:
            x,y = y,x
        rep = 0
        if a<x:
            rep += (x-a)*2
        if y<b:
            rep += (b-y)*2
        rep += (y-x)
        return rep
    N = I()
    AB = [LI()for _ in range(N)]
    ans = inf
    for i in range(N):
        s = AB[i][0]
        for j in range(N):
            g = AB[j][1]
            cur = 0
            for k in range(N):
                cur += length(AB[k][0],AB[k][1],s,g)
            ans = min(ans,cur)
    print(ans)
    return

def JOI7_D():
    M = I()
    S = [LI()for _ in range(M)]
    Ss = [(0,0)]
    curx,cury = S[0]
    for sx,sy in S[1:]:
        Ss.append((sx-curx,sy-cury))
        curx = sx; cury = sy
    
    N = I()
    X = [LI()for _ in range(N)]
    D = set()
    for i in range(N):
        cur = (X[i][0],X[i][1])
        D.add(cur)
    for i in range(N):
        flag = True
        curx, cury = X[i]
        for k in range(M):
            curx += Ss[k][0]
            cury += Ss[k][1]
            
            if not (curx, cury) in D:
                flag = False
                break
        if flag:
            
            ansx = X[i][0] - S[0][0]
            ansy = X[i][1] - S[0][1]
            print(ansx,ansy)
            return
    return

def ABC128_C():
    N, M = LI()
    S = [[]for _ in range(N)]
    for i in range(M):
        s = LI()
        for j in s[1:]:
            S[j-1].append(i)
    P = LI()
    
    loop = 2**N
    ans = 0
    for i in range(loop):
        p = [0]*M
        cur = []
        for j in range(N):
            if (1<<j)&i==(1<<j):
                cur.append(j)
        for k in cur:
            for l in S[k]:
                p[l] += 1
        flag = True
        for j in range(M):
            if p[j]%2!=P[j]:
                flag = False
        if flag:
            ans += 1
    print(ans)
    return

def ABC2_D():
    N, M = LI()
    V = set()
    for _ in range(M):
        x,y = LI()
        V.add((x,y))
    loop = 2**N
    ans = 0
    
    for i in range(loop):
        cur = []
        for j in range(N):
            if (1<<j)&i==(1<<j):
                cur.append(j+1)
        flag = True
        for k1,k2 in itertools.permutations(cur,2):
            if not ((k1,k2) in V or (k2,k1) in V):
                flag = False
                break
        if flag:
            ans = max(ans,len(cur))
    print(ans)
    return

def JOI7_E():
    R, C = LI()
    A = [LI()for _ in range(R)]
    loop = 2**R
    ans = 0
    for i in range(loop):
        rev = set()
        for j in range(R):
            if (1<<j)&i==(1<<j):
                rev.add(j)
        cur = 0
        for j in range(C):
            s = 0
            for k in range(R):
                if k in rev and A[k][j]==0:
                    s += 1
                elif (not k in rev) and A[k][j]==1:
                    s += 1
            cur += max(s,R-s)
        ans = max(ans,cur)
    print(ans)
    return

def square869120Contest4_B():
    N, K = LI()
    A = LI()
    ans = inf
    loop = 2**(N-1)
    for i in range(loop):
        look = set()
        for j in range(N-1):
            if (1<<j)&i==(1<<j):
                look.add(j+1)
        if len(look)<K-1:
            continue
        high = A[0]
        cur = 0
        flag = True
        for j in range(1,N):
            if not (j in look):
                if A[j]>high:
                    flag = False
                    break
            else:
                if high >= A[j]:
                    cur += (high - A[j] + 1)
                    high += 1
                else:
                    high = A[j]
        
        if not flag:
            continue
        ans = min(ans,cur)
    print(ans)
    return

def ABC145_C():
    N = I()
    X = [LI()for _ in range(N)]
    ans = 0
    c = 0
    for x in itertools.permutations(X):
        cur = 0
        c += 1
        for i in range(N-1):
            cur += ((x[i+1][0]-x[i][0])**2 + (x[i+1][1]-x[i][1])**2)**0.5
        ans += cur
    ans /= c
    print(ans)
    return

def ABC150_C():
    N = I()
    T = [i+1 for i in range(N)]
    P = LI()
    Q = LI()
    for i,t in enumerate(itertools.permutations(T)):
        flag_P = True
        flag_Q = True
        for j in range(N):
            if t[j]!=P[j]:
                flag_P = False
            if t[j]!=Q[j]:
                flag_Q = False
        if flag_P:
            a = i
        if flag_Q:
            b = i
    ans = abs(a-b)
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math,random
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    ABC150_C()

"""

"""

Solution (Python):
import sys
import numpy as np

n=int(sys.stdin.readline())


a=np.array([sys.stdin.readline().split() for i in range(2)],dtype='int64')

p,q=a[0],a[1]


def order(x):
    dp=[0]*(n+1)
    l=list(range(1,n+1))
    for i in range(n):
        dp[i+1]=dp[i]*len(l)+l.index(x[i])
        l.remove(x[i])
    return dp[n]

print(abs(order(p)-order(q)))

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=tuple(limii())
q=tuple(limii())

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

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

Solution (Python):
import itertools
N = int(input())
P = int(''.join(input().split()))
Q = int(''.join(input().split()))
Ns = list(itertools.permutations([str(i) for i in range(1,N+1)], N))
NP = 0
NQ = 0
for ni in Ns:
  nii = int(''.join(ni))
  if nii < P:
    NP += 1
  if nii < Q:
    NQ += 1
print(abs(NP - NQ))

Solution (Python):
from itertools import permutations
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
a=0
b=0
i=0
for x in permutations(range(1,N+1)):
	i+=1
	if list(x)==A:
		a=i
	if list(x)==B:
		b=i
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()))
p=0
q=0
i=0
for x in permutations(range(1,N+1)):
    i+=1
    if list(x)==P:
        p=i
    if list(x)==Q:
        q=i
print(abs(p-q))

Solution (Python):
import itertools

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

a = 0
b = 0
deck = list(map(str, range(1,N+1)))
cnt = 0
for s in itertools.permutations(deck):
	ss = "".join(s)
	if ss == P:
		a = cnt
	if ss == Q:
		b = cnt

	cnt += 1

print(abs(a-b))

Solution (Python):
import itertools

num = int(input())
num_list_1 = list(map(int,input().split()))
num_list_2 = list(map(int,input().split()))

num_list = list(itertools.permutations(range(1,num+1)))
count = len(num_list)
num_list_copy_1 = []

for i in range(0,num):
  num_list_copy = []
  for j in range(0,count):
    if num_list_1[i] == num_list[j][i]:
      num_list_copy.append(num_list[j])
      
    elif num_list_1[i] > num_list[j][i]:
      num_list_copy_1.append(num_list[j])
  
  num_list = num_list_copy
  count = len(num_list_copy)
  
count_a = len(num_list_copy_1)+1
  
num_list = list(itertools.permutations(range(1,num+1)))
count = len(num_list)
num_list_copy_2 = []

for i in range(0,num):
  num_list_copy = []
  for j in range(0,count):
    if num_list_2[i] == num_list[j][i]:
      num_list_copy.append(num_list[j])
      
    elif num_list_2[i] > num_list[j][i]:
      num_list_copy_2.append(num_list[j])
  
  num_list = num_list_copy
  count = len(num_list_copy)
  
count_b = len(num_list_copy_2)+1

print(abs(count_a - count_b))

Solution (Python):
import sys
import itertools

sys.setrecursionlimit(1000000)
input = lambda: sys.stdin.readline().rstrip()

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

p = itertools.permutations([i + 1 for i in range(N)])

for i, j in enumerate(p):
    if all(x == y for x, y in zip(j, P)):
        a = i
    if all(x == y for x, y in zip(j, Q)):
        b = i

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

pi, qi = -1, -1
for i, perm in enumerate(permutations(range(1, n + 1))):
    if perm == p:
        pi = i
        if qi != -1:
            break
    if perm == q:
        qi = i
        if pi != -1:
            break
print(abs(pi - qi))

Solution (Python):
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)
i=0
for v in itertools.permutations(X,n):
    i+=1
    if list(v)==P:
        p=i
    if list(v)==Q:
        q=i
print(abs(p-q))

Solution (Python):
import math

n=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
P_s=sorted(P)
Q_s=sorted(Q)
num_p=0
num_q=0
for i in range(n):
    num_p+=(P_s.index(P[i]))*math.factorial(n-i-1)
    num_q+=(Q_s.index(Q[i]))*math.factorial(n-i-1)
    P_s.remove(P[i])
    Q_s.remove(Q[i])

print(abs(num_p-num_q))

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

from itertools import permutations

all = list(permutations(list(map(str,range(1,n+1))), n))
all = list(map(lambda x: ''.join(x), all))
all.sort()
print(abs(all.index(p) - all.index(q)))

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

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

Solution (Python):
n=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
A=[]
B=[]
C=[1]
for i in range(1,n+1):
  A.append(i)
  B.append(i)
  if i!=1:
    C.append(C[-1]*i)
a=0
b=0
for i in range(n-1):
  a=a+C[-2-i]*(A.index(P[i]))
  A.remove(P[i])
  b=b+C[-2-i]*(B.index(Q[i]))
  B.remove(Q[i])
print(abs(a-b))

Solution (Python):
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
l = [i + 1 for i in range(n)]
itt = sorted(list(itertools.permutations(l, n)))
counter = 0
for list_ in itt:
    list_ = list(list_)
    if list_ == p:
        a = counter
    if list_ == q:
        b = counter
    counter += 1
print(abs(b - a))

Solution (Python):
import itertools as it

N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
a = -1
b = -1

li = list(it.permutations(P,N))
li.sort()
for n in range(len(li)) :
    l = li[n]
    
    is_P = True
    is_Q = True
    for i in range(N) :
        if (P[i] != l[i]) :
            is_P = False
        if (Q[i] != l[i]) :
            is_Q = False
        if (not(is_P) and not(is_Q)) :
            break
    if (is_P) :
        a = n+1
    if (is_Q) :
        b = n+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()))

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

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

print(abs(p - q))

Solution (Python):
import sys
input = sys.stdin.readline
from itertools import permutations

def main():
    N = int(input())
    p = tuple(map(int,input().split()))
    q = tuple(map(int,input().split()))
    p_i = 0
    q_i = 0
    perm = list(permutations(list(range(1,N+1))))
    for i in range(len(perm)):
        if perm[i] == p:
            p_i = i
        if perm[i] == q:
            q_i = i
    print(abs(p_i-q_i))
    return


if __name__ == '__main__':
    main()

Solution (Python):
import itertools
import math
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
if p== q:
    print(0)
else:
    sample=[]
    for i in range(1,n+1):
        sample.append(i)
    perm=list(itertools.permutations(sample))
    for i in range(math.factorial(n)):
        perm[i]=list(perm[i])
    ans=[]
    for i in range(math.factorial(n)):
        if list(perm[i]) == p or list(perm[i]) == q :
            ans.append(i+1)
            if len(ans) == 2:
                break

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

Solution (Python):
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
import itertools
a=[list(i) for i in itertools.permutations(range(1,n+1))]
import bisect as bi
x=bi.bisect_right(a,p)
y=bi.bisect_right(a,q)
print(abs(x-y))

Solution (Python):

import sys
import itertools


def solve(N: int, P: "List[int]", Q: "List[int]"):
    P = tuple(P)
    Q = tuple(Q)
    a = 0
    b = 0
    permutations = itertools.permutations(range(1, N + 1))
    for i, permutation in enumerate(permutations):

        if P == permutation:
            a = i
        if Q == permutation:
            b = i

    result = abs(a - b)
    print(result)
    return



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):
import numpy as np
import itertools

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

Num = range(1,N+1)

Number = str(''.join(map(str,Num)))


per_num=list(itertools.permutations(Number))
pernum_arr = np.ones(len(per_num))
for i in range(len(per_num)): 
    pernum_arr[i] = int(''.join(map(str,per_num[i])))
P = int(''.join(map(str,P)))
Q = int(''.join(map(str,Q)))

ans = abs(np.where(pernum_arr==P)[0]-np.where(pernum_arr==Q)[0])
print(ans[0])

Solution (Python):
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
from itertools import permutations
l = list(permutations(range(1,N+1)))
print(abs(l.index(P) - l.index(Q)))

Solution (Python):
from itertools import permutations
n=int(input())
P=list(input().split())
Q=list(input().split())
A=[]
for i in list(permutations(P)):
   A.append(int("".join(i)))
A.sort()
print(abs(A.index(int("".join(P)))-A.index(int("".join(Q)))))

Solution (Python):
n=int(input())
perm=[list(range(1,n+1))]
fact=1
from copy import copy
for i in range(1,n+1):
  fact*=i 
for i in range(1,fact):
  cur=perm[-1].copy()
  for j in range(n-1,-1,-1):
    if cur[j]<max(cur[j:]):
      aux=cur[j:].copy()
      aux.sort()
      for k in range(len(aux)):
        if aux[k]>cur[j]:
          cur[j]=aux[k]
          aux.remove(aux[k])
          break
      cur[j+1:]=aux
      break
  perm.append(cur)
x=input().split()
y=input().split()
p=[]
q=[]
for k in range(n):
  p.append(int(x[k]))
  q.append(int(y[k]))

a=[]
for i in range(fact):
  if perm[i] in [p,q]:
    a.append(i)
if len(a)==1:
  print(0)
else:
  print(abs(a[0]-a[1]))

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