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())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))

for i, x in enumerate(permutations([i+1 for i in range(n)])):
    if x == p:
        a = i
    if x == q:
        b = i
print(abs(a-b))

Solution (Python):
import itertools

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

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

i_a = 0
i_b = 0

for i, p in enumerate(itertools.permutations(nums)):
    if a == list(p):
        i_a = i+1
    if b == list(p):
        i_b = i+1

    if i_a and i_b:
        break

print(abs(i_a - i_b))

Solution (Python):
from copy import deepcopy
import math
import string
import collections
from collections import Counter
from collections import deque
from decimal import Decimal
import sys
import fractions
from operator import itemgetter
import itertools
import copy


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


def nCr(n, r):
    return math.factorial(n)//(math.factorial(n-r)*math.factorial(r))


def has_duplicates2(seq):
    seen = []
    for item in seq:
        if not(item in seen):
            seen.append(item)
    return len(seq) != len(seen)


def divisor(n):
    divisor = []
    for i in range(1, n+1):
        if n % i == 0:
            divisor.append(i)
    return divisor



dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]

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

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

x = list(itertools.permutations(seq))
xx = sorted(x)

for i in range(math.factorial(n)):
    a = map(str, list(xx[i]))
    b = "".join(map(str, a))
    c = int("".join(map(str, b)))
    
    if c == p_int:
        p_ans = i+1
    if c == q_int:
        q_ans = i+1
print(abs(p_ans-q_ans))

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

Solution (Python):
from itertools import groupby, accumulate, product, permutations, combinations
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))

n = 1
for p in permutations(range(1,N+1),N):
    if list(p)==P:
        a = n
    if list(p)==Q:
        b = n
    n += 1
ans = abs(a-b)
print(ans)

Solution (Python):




from itertools import combinations,permutations 

from collections import deque,defaultdict











import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n = I()
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
nya = [i+1 for i in range(n)]

jun = []
for a in permutations(nya):
    jun.append(a)
for i in range(len(jun)):
    if jun[i] == P:
        p = i
    if jun[i] == Q:
        q = i
print(abs(p-q))

Solution (Python):
import itertools
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
p = 0
q = 0
c = 0
for e in itertools.permutations([k+1 for k in range(N)], N):
    c += 1
    if e == P:
        p = c
    if e == Q:
        q = c
    if p*q > 0:
        break
print(abs(p-q))

Solution (Python):


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n=I()
lisp=tuple(LI())
lisq=tuple(LI())
x=[i for i in range(1,n+1)]
u=permutations(x)
count=0
for i in u:
    if i==lisp:
        P=count
    if i==lisq:
        Q=count
    count+=1
print(abs(P-Q))

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

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

lst = []
for v in itertools.permutations(range(1,n+1)):
    lst.append(''.join([str(i) for i in v]))

print(abs(lst.index(''.join([str(i) for i in pl]))-lst.index(''.join([str(i) for i in ql]))))

Solution (Python):
from itertools import permutations
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
A = sorted(P)
cnt = 0
for x in permutations(A,N):
    x = list(x)
    if x==P:
        a = cnt
    if x==Q:
        b = cnt
    cnt += 1
print(abs(a-b))

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

import itertools
X= []
a = 0
b = 0
for p in itertools.permutations(range(1, n+1)):
    for i in range(n):
        if p[i] < P[i]:
            a += 1
            break
        elif p[i] > P[i]:
            break
        else:
            continue
    for i in range(n):
        if p[i] < Q[i]:
            b += 1
            break
        elif p[i] > Q[i]:
            break
        else:
            continue

print(abs((a+1)-(b+1)))

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

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

for t in permutations(range(1, N+1)):
    if list(t)==P:
        a = c
    
    if list(t)==Q:
        b = c
    
    c += 1

print(abs(a-b))

Solution (Python):
from itertools import permutations

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

for i,j in enumerate(permutations(li)):
    if j == p:
        num_p = i
    if j == q:
        num_q = i

print(abs(num_p-num_q))

Solution (Python):
import itertools

n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
l=[i for i in range(1,n+1)]
j = itertools.permutations(l, n)

a=0
b=0
for num,i in enumerate(j):
    if(list(i)==p):a=num
    if(list(i)==q):b=num

print(abs(a-b))

Solution (Python):
import math

N = int(input())

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

def check(A):
    L = [j+1 for j in range(N)]
    ans = 0
    for i in range(N):
        a = L.index(A[i])
        ans += a*math.factorial(N-1-i)
        L.pop(a)
    return ans
p = check(P)
q = check(Q)
print(abs(p-q))

Solution (Python):
import itertools
import math
N = int(input())
P = ''.join(input().split())
Q = ''.join(input().split())
np = sorted(list(map(lambda x: ''.join(x), itertools.permutations([str(i+1) for i in range(N)]))))
print(abs((np.index(P)+1)-(np.index(Q)+1)))

Solution (Python):
import math

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

for i in range(n):
  orderp+=(p[i]-1)*math.factorial(n-i-1)
  orderq+=(q[i]-1)*math.factorial(n-i-1)
  for j in range(i+1,n):
    if p[j]>p[i]:
      p[j]-=1
    if q[j]>q[i]:
      q[j]-=1
  
  


print(abs(orderp-orderq))

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

for i,p in enumerate(permutations(range(1,N+1))):
    if p==P:
        a=i
    if p==Q:
        b=i
print(abs(a-b))

Solution (Python):
import itertools
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
lis=[x for x in range(1,n+1)]
permutation=itertools.permutations(lis)
cnt=0
a=0
b=0
for  case in permutation:
  case=list(case)
  cnt+=1
  if case == p:
    a=cnt
  if case == q:
    b=cnt
 
    
print(abs(a-b))

Solution (Python):

import math
import itertools
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
ans1=n
ans2=n
x = [i for i in range(1, n+1)]
for i in itertools.permutations(x,n):
    if p < list(i):
        ans1 -= 1
    if q < list(i):
        ans2 -= 1

print(abs(ans1-ans2))

Solution (Python):



import itertools

n = int(input())
p_l = [int(x) for x in input().split()]
q_l = [int(x) for x in input().split()]

per = itertools.permutations(list(range(1,n+1)))
a = 0
b = 0

for i,order in enumerate(per):
    if p_l == list(order):
        a = i
    if q_l == list(order):
        b = i

print(abs(a-b))

Solution (Python):
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
a=1
b=1
n1=1
for i in range(n):
    n1=n1*(i+1)
for i in range(n):
    t=0
    i1=1
    for j in range(i+1):
        i1=i1*(n-j)
    for j in range(n):
        if i<j and p[i]>p[j]:
            t+=1
    a+=t*n1//i1
for i in range(n):
    t=0
    i1=1
    for j in range(i+1):
        i1=i1*(n-j)
    for j in range(n):
        if i<j and q[i]>q[j]:
            t+=1
    b+=t*n1//i1
c=a-b
if c>0:
    print(c)
else:
    print(-c)

Solution (Python):




from __future__ import division, print_function 

import sys
import os
from collections import Counter, deque, defaultdict
import itertools
import math
import io


"""Uncomment modules according to your need"""













if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip



"""value of mod"""
MOD = 998244353
mod = 10**9 + 7

"""Uncomment next 4 lines if doing huge recursion"""




def prepare_factorial(mod=mod):
    """ returns two lists, factorial and inverse factorial modulo argument by default 10**9 +7 """
    
    fact = [1]
    for i in range(1, 200005):
        fact.append((fact[-1] * i) % mod)

    ifact = [0] * 200005
    ifact[200004] = pow(fact[200004], mod - 2, mod)
    for i in range(200004, 0, -1):
        ifact[i - 1] = (i * ifact[i]) % mod

    return fact, ifact

def modinv(n, p):
    """ returns N inverse modulo p """
    return pow(n, p - 2, p)

def ncr(n, r,  fact, ifact):
    """ takes 4 arguments: n , r and factorial and inverse factorial lists"""
    t = (fact[n] * (ifact[r]*ifact[n-r]) % MOD)% MOD
    return t


def get_n(Sum):    
    """this function returns the maximum n for which Summation(n) <= Sum"""
    ans = (-1 + sqrt(1 + 8*Sum))//2
    return ans

def sieve(n):
    """ returns a list of prime numbers till n """
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r



def divs(n, start=1):
    """ returns a list of all divisors till n """
    divisors = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors



def divn(n, primes):
    """ returns the number of divisors, two arguments n and the sieve till n """
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t



def lrfind(d, x, default=-1):
    """ Takes 2 arguments an iterable and an element. returns a tuple (firstoccurence,lastoccurence) -1 if not found """
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1: left = i
            right = i
    if left == -1:
        return default, default
    else:
        return left, right

def gcd(x, y): 
    """ returns greatest common divisor of x and y """
    while y:
        x, y = y, x % y
    return x

def check_sorted(a):
    ''' returns True/False '''
    for i in range(len(a)-1):
        if a[i]>a[i+1]:
            return False
    return True
def ceil(n, k=1): return n // k + (n % k != 0) 
def input(): return sys.stdin.readline().strip()
def ii(): return int(input()) 
def mi(): return map(int, input().split()) 
def li(): return list(map(int, input().split())) 
def lw(): return input().split() 
def lcm(a, b): return abs(a * b) // gcd(a, b) 
def prr(a, sep=' ', end='\n'): print(sep.join(map(str, a)), end=end) 
def dd(): return defaultdict(int) 
def ddl(): return defaultdict(list) 
def write(s): return sys.stdout.write(s)














def main():
    
    n=ii()
    p=li()
    q=li()
    l=list(itertools.permutations(sorted(p)))
    print(abs(l.index(tuple(p))-l.index(tuple(q))))













    
""" -------- Python 2 and 3 footer by Pajenegod and c1729 ---------"""

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill();
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)


class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s: self.buffer.write(s.encode('ascii'))
            self.read = lambda: self.buffer.read().decode('ascii')
            self.readline = lambda: self.buffer.readline().decode('ascii')


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')



""" main function"""

if __name__ == '__main__':
    main()

Solution (Python):
import itertools

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

lis = [i for i in range(1, N+1)]
m = []

for i in itertools.permutations(lis, len(lis)):
    m.append(i)

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

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)))
p = permutations.index(P)
q = permutations.index(Q)


print(abs(p-q))

Solution (Python):


import bisect




def solve(N, Ps, Qs):
    def dfs(s, perm):
        if len(s) == N + 1:
            perm.append(int(s))
            return perm
        for i in range(1, N + 1):
            if not str(i) in s:
                perm = dfs(s + str(i), perm)
        return perm

    perm = dfs('0', [])

    p = int(''.join(Ps))
    q = int(''.join(Qs))

    print(abs(bisect.bisect_right(perm, p) - bisect.bisect_right(perm, q)))


if __name__ == '__main__':
    N = int(input())
    Ps = input().split()
    Qs = input().split()
    solve(N, Ps, Qs)

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

p = 0
q = 0
for i,r in enumerate(itertools.permutations([i+1 for i in range(N)])):
    if P == r:
        p = i+1
    if Q == r:
        q = i+1
    if p and q:
        break

print(abs(p-q))

Solution (Python):
import itertools

N = int(input())
P = input().replace(' ','')
Q = input().replace(' ','')

item = []
for i in range(1,N + 1):
    item.append(str(i))
lst = list(itertools.permutations(item))

item2 = []
for l in lst:
    item2.append(''.join(l))

a = abs(item2.index(P) - item2.index(Q))
print(a)

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

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

Solution (Python):
import itertools
N = int(input())
P = [p for p in map(int,input().split())]
Q = [q for q in map(int,input().split())]

NL = [n for n in range(1,N+1)]

V = [list(v) for v in itertools.permutations(NL)]

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

print(ans)

Solution (Python):
from itertools import permutations

def main():
    n = int(input())
    p = list(map(int, input().split()))
    q = list(map(int, input().split()))
    ns = [i for i in range(1,n+1)]
    l = list(permutations(ns,n))
    pt = tuple(p)
    qt = tuple(q)
    print(abs(l.index(pt)-l.index(qt)))

if __name__ == "__main__":
    main()

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)
l=list(itertools.permutations(l))
l=sorted(l)
k=1
for i in range(1,n+1):
    k*=i
pp=0
qq=0
if p==q:
    print(0)
else:
    for j in range(k):
        if l[j]==p:
            pp=j+1
        elif l[j]==q:
            qq=j+1
    print(abs(pp-qq))

Solution (Python):
from itertools import permutations

def readinput():
    n=int(input())
    P=tuple(map(int,input().split()))
    Q=tuple(map(int,input().split()))
    return n,P,Q

def main(n,P,Q):
    permlist=permutations(range(1,n+1))
    sortedList=sorted(permlist)
    
    np=sortedList.index(P)
    nq=sortedList.index(Q)
    return abs(np-nq)

if __name__=='__main__':
    n,P,Q=readinput()
    ans=main(n,P,Q)
    print(ans)

Solution (Python):
import itertools
X = int(input())
P = tuple(map(int, input().split(" ")))
Q = tuple(map(int, input().split(" ")))
comb = list(itertools.permutations(range(1, X+1),X))
a = comb.index(P)
b = comb.index(Q)
print(abs(a-b))

Solution (Python):
from itertools import permutations

def solve(N, P, Q):
    vals = [i for i in range(1, N + 1)]
    perms = list(permutations(vals))
    print(abs(perms.index(P) - perms.index(Q)))

if __name__ == "__main__":
    N = int(input())
    P = tuple(map(int, input().split()))
    Q = tuple(map(int, input().split()))
    solve(N, P, Q)

Solution (Python):
from collections import deque

def solve(N, P, Q):
    stack = deque()
    vals = [i for i in range(1, N + 1)]
    for idx, next_val in enumerate(vals):
        stack.append([[next_val], vals[: idx] + vals[idx + 1:]])
    a, b = -1, -1
    counter = 0
    while stack:
        cur_list, rest = stack.popleft()
        if not rest:
            counter += 1
            a = counter if cur_list == P else a
            b = counter if cur_list == Q else b
            if 0 < a and 0 < b:
                print(abs(a - b))
                return

        for idx, next_val in enumerate(rest):
            stack.append([cur_list + [next_val], rest[: idx] + rest[idx + 1:]])

if __name__ == "__main__":
    N = int(input())
    P = list(map(int, input().split()))
    Q = list(map(int, input().split()))
    solve(N, P, Q)

Solution (Python):
import itertools

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

for i in range(1,N+1):
    order.append(i)



count = 0
for vect in itertools.permutations(order):
    
    count +=1
    if vect == P:
        a = count
    if vect ==Q:
        b = count

print(abs(a-b))

Solution (Python):
import itertools

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

P = int(''.join(P))
Q = int(''.join(Q))

lst = []
for a in list(itertools.permutations(range(1, N + 1))):
    a = [str(b) for b in a]
    a = ''.join(a)
    a = int(a)

    lst.append(a)

lst.sort()
dic = {}
for i, a in enumerate(lst):
    dic[a] = i + 1

ans = abs(dic[P] - dic[Q])
print(ans)

Solution (Python):
import itertools

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

cnt = 0
for i in list(itertools.permutations(N)):
    cnt += 1
    if i == P:
        a = cnt
    if i == Q:
        b = cnt
        
print(abs(a-b))

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

from itertools import permutations

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

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

Solution (Python):
from collections import deque
import numpy as np
from math import factorial

n = int(input())

ps = deque(map(lambda x: int(x) - 1, input().split()))

qs = deque(map(lambda x: int(x) - 1, input().split()))

def l_to_num(l):
    ans = 0
    
    n = len(l)
    order = np.arange(n)
    n -= 1
    fn = factorial(n)
    for _ in list(range(n)):
        tmp = l.popleft()
        ans += order[tmp] * fn
        fn //= n
        order[tmp] = 1 << 31
        order[tmp+1:] -= 1
        n -= 1
    
    return ans

print(abs(l_to_num(ps) - l_to_num(qs)))

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

A = list(permutations(P))
A.sort()
print(abs(A.index(tuple(P)) - A.index(tuple(Q))))

Solution (Python):
import itertools
n = int(input())
P = list(map(str, input().split()))
Q = list(map(str, input().split()))
p = ''
for e in P:
  p += e
p = int(p)
q = ''
for e in Q:
  q += e
q = int(q)
l = [str(i) for i in range(1, n + 1)]
r = itertools.permutations(l, n)
a = []
for v in r:
  s = ''
  for e in v:
    s += e
  s = int(s)
  a.append(s)
print(abs(a.index(p) - a.index(q)))

Solution (Python):
import itertools

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

n = 0
s = 0

S = list(itertools.permutations(range(1, N+1)))
for i, item in enumerate(S):
    if P == item:
        n = i
    if Q == item:
        s = i
    if s > 0 and n > 0:
        break

print(abs(s-n))

Solution (Python):
import itertools

n = int(input())
p_list = list(map(int, input().split()))
q_list = list(map(int, input().split()))

data = sorted(q_list)

l = list(itertools.permutations(data, n))
for i in range( len(l) ):
    l[i] = list(l[i])

print( abs( l.index(p_list) - l.index(q_list) ) )

Solution (Python):
import itertools

N = int(input())
NP = list(itertools.permutations(range(N), N))
P = tuple(map(lambda s: int(s) - 1, input().split()))
Q = tuple(map(lambda s: int(s) - 1, input().split()))

ans = abs(NP.index(P) - NP.index(Q))
print(ans)

Solution (Python):




import sys
from fractions import gcd
import math
from math import ceil,floor
import collections
from collections import Counter
import itertools











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

Ptuple = tuple(P)
Qtuple = tuple(Q)

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

count = 0
num = 1
tmp1 = 0
tmp2 = 0

for j in itertools.permutations(tmp):
    if j == Ptuple:
        tmp1 = num
        count += 1
    if j == Qtuple:
        tmp2 = num
        count += 1
    if count == 2:
        print(abs(tmp1-tmp2))
        sys.exit()
    num += 1

Solution (Python):
import itertools

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

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

cp = 0
cq = 0

for i in range(len(p)):
    if p[i] == P:
        cp = i + 1
    if p[i] == Q:
        cq = i + 1

print(abs(cp-cq))

Solution (Python):

from itertools import permutations
N=int(input())
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
num=[i for i in range(1,N+1)]
L=permutations(num,N)
L=sorted(L)

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 itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
r = sorted(p)
r = list(itertools.permutations(r, n))
a, b = -1, -1
idx = 0
while True:
    for i in range(n):
        if r[idx][i] != p[i]:
            break
        if i == n - 1:
            a = idx
    for i in range(n):
        if r[idx][i] != q[i]:
            break
        if i == n - 1:
            b = idx
    if a != -1 and b != -1:
        break
    idx += 1
print(abs(a-b))

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

import itertools
import collections
seq = [i+1 for i in range(n)]
li = itertools.permutations(seq)
dic = collections.defaultdict()
for i,  each in enumerate(li):
    dic[each] = i

print(abs(dic[p] - dic[q]))

Solution (Python):
import itertools

n = int(input())
a = [ str(x) for x in range(1,n+1)]
jun = list(itertools.permutations(a))
p = list(map(str, input().split()))
q = list(map(str, input().split()))
p = ''.join(p)
q = ''.join(q)
a = []

for i in jun:
    i = list(i)
    a.append(''.join(i))
x = a.index(p)
y = a.index(q)
print(abs(x-y))

Solution (Python):
import itertools
n=int(input())
p=tuple(map(int,input().split()))
q=tuple(map(int,input().split()))
per=list(itertools.permutations(range(1,n+1)))
a=0
b=0
for num,i in enumerate(per):
    if i==p: a=num+1
    if i==q: b=num+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()))
comb = sorted(list(permutations([i for i in range(1, N+1)], N)))
print(abs((comb.index(P) + 1) - (comb.index(Q) + 1)))

Solution (Python):
from itertools import permutations
import numpy as np
n=int(input())
nn=np.arange(1,n+1).tolist()
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))

s=list(permutations(nn))

a=s.index(a)
b=s.index(b)
print(abs(a-b))

Solution (Python):
n=int(input())
import math
p=list(map(int,input().split()))
q=list(map(int,input().split()))
pn=0
qn=0
for i in range(n):
  pn+=math.factorial(n-i-1)*(p[i]-1)
  qn+=math.factorial(n-i-1)*(q[i]-1)
  po=p[i]
  qo=q[i]
  p = [j-1 if j>po else j for j in p]
  q = [k-1 if k>qo else k for k in q]
print(abs(pn-qn))

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)]
count = 1
count_p = 0
count_q = 0

for v in itertools.permutations(l):
    
    if v == P:
        count_p = count
    if v == Q:
        count_q = count

    if (count_p != 0) & (count_q != 0):
        ans = abs(count_p - count_q)
        break
    else:
        count += 1

print(ans)

Solution (Python):
from itertools import permutations

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

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

C = list(permutations(N))

for i, c in enumerate(C):
    if list(c) == list(P):
        f = i
    if list(c) == Q:
        s = i
print(abs(s-f))

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

fact = [1]
for i in range(1,8+1):
  fact.append(fact[i-1]*i)


def seq_to_index(seq):
  
  seq_len=len(seq)
  unused_val=[i+1 for i in range(seq_len)]
  index=0
  for i in range(seq_len):
  
    
    
    coeff = seq[i]
    coeff_index_in_unused = unused_val.index(coeff)
    index+=coeff_index_in_unused*fact[seq_len-1-i]
    
    
    
    
    
    

    unused_val.remove(coeff)

  
  return index
    
n=input()

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

pindex=seq_to_index(P)
qindex=seq_to_index(Q)




print(qindex-pindex if qindex>pindex else pindex-qindex)

Solution (Python):
import itertools

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

perms = list(itertools.permutations(range(1, n+1)))
a = perms.index(p)
b = perms.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()))

n_p = list(itertools.permutations([i + 1 for i in range(n)], n))
a = -1
b = -1
for i in n_p:
    if a != -1 and b != -1:
        break
    if i == p:
        a = n_p.index(i)
    if i == q:
        b = n_p.index(i)

print(abs(a - b))

Solution (Python):
import sys
import itertools

input = sys.stdin.readline

def slove():
    n = int(input())
    P = tuple(map(int,input().split()))
    Q = tuple(map(int,input().split()))
    """
    print(P)
    print(Q)
    """
    count = 0
    for item in itertools.permutations(range(1,1+n)):
        if P == item:
            a = count
        if Q == item:
            b = count
        count += 1
    print(abs(a-b))


if __name__ == "__main__":
    slove()

Solution (Python):
def exclude(cs, s):
    return [x for i, x in enumerate(cs) if i not in s]


def createLine(line, length):
    if length <= 0 or length > len(line):
        return []
    result = []
    _createLine(line, length, [], result)
    
    return result


def _createLine(line, length, progress, result):
    if length == 0:
        result.append(progress)
        return

    for i in range(len(line)):
        _createLine(exclude(line, [i]), length - 1,
                    progress + [line[i]], result)


N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
line = [i for i in range(1, N + 1)]
string = createLine(line, N)
print(abs(string.index(Q)-string.index(P)))

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

import itertools

a, b = 0, 0
for i, s in enumerate(itertools.permutations(sorted(P))):
  if s == tuple(P):
    a = i
  if s == tuple(T):
    b = i

print(abs(a-b))

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

pval = [i for i in range(1, N+1)]
qval = [i for i in range(1, N+1)]

pcount, qcount = 0, 0
for x, y in zip(p, q):
    pval.remove(int(x))
    pcount += len([i for i in pval if i <= int(x)-1])*math.factorial(len(pval))
    qval.remove(int(y))
    qcount += len([i for i in qval if i <= int(y)-1])*math.factorial(len(qval))
    
print(abs(pcount-qcount))