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
import sys
import heapq
from collections import Counter
from collections import deque
from fractions import gcd
from math import factorial
from math import sqrt
INF = 1 << 60
sys.setrecursionlimit(10 ** 6)

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())



n = int(input())
x = [i for i in range(1, n + 1)]
p = list(map(int, input().split()))
q = list(map(int, input().split()))
a = 0
b = 0
cnt = 0
a_finished = False
b_finished = False
for i in permutations(x):
    
    if a_finished and b_finished:
        break
    if list(i) == p:
        a = cnt
        a_finished = True 
    if list(i) == q:
        b = cnt
        b_finished = True
    cnt += 1
ans = abs(a - b)
print(ans)

Solution (Python):
import itertools
n = int(input())
plis = list(map(int, input().split()))
qlis = list(map(int, input().split()))
lis = list(itertools.permutations(range(1, n+1)))
n = 1
for i in lis:
    if list(i) == plis:
        a = n
    if list(i) == qlis:
        b = n
    n += 1
print(abs(a-b))

Solution (Python):
import math

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

dig=[1]*(N+1)
dig[0]=0
a=1
for i,pp in enumerate(p):
    a+=sum(dig[:pp])*math.factorial(N-i-1)
    dig[pp]=0

dig=[1]*(N+1)
dig[0]=0
b=1
for i,qq in enumerate(q):
    b+=sum(dig[:qq])*math.factorial(N-i-1)
    dig[qq]=0
print(abs(a-b))

Solution (Python):
import os
from itertools import permutations

def main():
	p_score, q_score, count = 0,0,0
	string = ""
	num = int(input())
	p_num = tuple(list(map(str, input().split())))
	q_num = tuple(list(map(str, input().split())))
	for i in range(1,num+1):
		string  = string + str(i) 
	list_ = list(permutations(string, num))
	
	for i in list_:

		count += 1
		if p_num == i:
			q_score = count
		if q_num == i:
			p_score = count
	
		
	print(abs(q_score - p_score))
		


if __name__ == '__main__':
	main()

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

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)))
a = p.index(P)
b = p.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()))
num = []
for i in range(1,n+1):
    num.append(i)
ans = []
for i in list(itertools.permutations(num)):
    ans.append(i)
print(abs(ans.index(P)-ans.index(Q)))

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

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

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(range(1,n+1), n):
    cnt +=1
    if(p==v):
        a = cnt
    if(q==v):
        b = cnt

print(abs(a-b))

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(range(1,n+1), n):
    cnt +=1
    if(p==v):
        a = cnt
    if(q==v):
        b = cnt

print(abs(a-b))

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

for i, v in enumerate(itertools.permutations(range(1,n+1))):
    if p==v:
        s=i
    if q==v:
        t=i
print(abs(s-t))

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

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

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

Solution (Python):
import sys
input = sys.stdin.readline
input = sys.stdin.buffer.readline
def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))



from itertools import permutations


def main():
	n=II()
	P=TI()
	Q=TI()
	ans=0
	for i,p in enumerate(permutations(range(1,n+1),n)):
		if P==p:
			ans-=i
		if Q==p:
			ans+=i
	print(abs(ans))




if __name__ == "__main__":
	main()

Solution (Python):
import itertools

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

x = list(range(N))
x = [y+1 for y in x]
p = itertools.permutations(x)
a=None
b=None
cnt = 1
for l in p:
    if list(l) == P:
        a = cnt
    if list(l) == Q:
        b = cnt
    if a!=None and b!=None:
        print(abs(a-b))
        exit()
    cnt += 1

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

import itertools

A = list(range(1, N + 1))
L = []

for i in itertools.permutations(A, N):
    L.extend([list(i)])

for index, value in enumerate(L):
    if L[index] == P:
        p = index
    if L[index] == Q:
        q = index

print(abs(p - q))

Solution (Python):
import itertools


def main():
    N = [i for i in range(1, int(input()) + 1)]
    P = tuple(map(int, input().split(' ')))
    Q = tuple(map(int, input().split(' ')))
    x, y = 0, 0
    for enum, n in enumerate(itertools.permutations(N)):
        if n == P:
            x = enum + 1
        if n == Q:
            y = enum + 1
        if x > 0 and y > 0:
            break
    print(abs(x - y))


if __name__ == '__main__':
    main()

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

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

from itertools import permutations

li=[]
for i in permutations(A, n):
    li.extend([list(i)])
    
for i, v in enumerate(li):
    if li[i] == p:
        s = i
    if li[i] == q:
        t = i
print(abs(s-t))

Solution (Python):
from itertools import permutations
n = int(input())
p = tuple(i for i in map(int, input().split()))
q = tuple(i for i in map(int, input().split()))
count = 0
for i in permutations([j for j in range(1, n+1)], n):
    if p == i:
        p_c = count
    if q == i:
        q_c = count
    count += 1
print(abs(p_c-q_c))

Solution (Python):
import itertools

N = int(input())

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

p = list(itertools.permutations(l, N))

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

a = p.index(P)
b = p.index(Q)

print(abs(b-a))

Solution (Python):
from itertools import permutations

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

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

print(ans)

Solution (Python):
from itertools import permutations as per
n, *w = map(int, open(0).read().split())
l = list(per(range(1, n+1)))
def F(_):
  return l.index(tuple(_))
print(abs(F(w[:n]) - F(w[n:])))

Solution (Python):

N = int(input())
S = [tuple(map(str, input().split())) for i in range(2)]

from itertools import permutations
kaijo =[str(i) for i in range(1,N+1)]
junretu = [t for t in permutations(kaijo) ]
nanbannme_1 =junretu.index(S[0])
nanbannme_2 =junretu.index(S[1])
print(abs(nanbannme_1 - nanbannme_2))
"""
print(nanbannme_1)
print(nanbannme_2)
print(junretu)
print(S)
"""

Solution (Python):
from itertools import permutations

def resolve():
    N=int(input())
    P = tuple([int(i) for i in input().split()])
    Q = tuple([int(i) for i in input().split()])

    x = list(permutations(range(1,N+1),N))
    x.sort()
    p =0
    q =0
    for i,v in enumerate(x):
        if P == v:
            
            p = i
        if Q == v:
            
            q = i
    print(abs(p-q))


if __name__ == "__main__":
    resolve()

Solution (Python):
import math

n = int(input())
arraya = list(map(int,input().split()))
numsa = [i+1 for i in range(n)]
arrayb = list(map(int,input().split()))
numsb = [i+1 for i in range(n)]

cnta = 1
for i in range(n):
  num = arraya[i]
  mae = numsa.index(num)
  ushiro = math.factorial(n-(i+1))
  cnta += mae*ushiro
  numsa.remove(num)
  
cntb = 1
for i in range(n):
  num = arrayb[i]
  mae = numsb.index(num)
  ushiro = math.factorial(n-(i+1))
  cntb += mae*ushiro
  numsb.remove(num)
  
print(abs(cnta-cntb))

Solution (Python):


import sys












from itertools import permutations

def main():
    mod = 10000007                  
    inf = float('inf')
    input = sys.stdin.readline      
    sys.setrecursionlimit(10**6)    
    def ii():  return int(input())
    def mi():  return map(int, input().rstrip().split())
    def lmi(): return list(map(int, input().rstrip().split()))
    def li():  return list(input().rstrip())
    
    n = ii()
    p = tuple(mi())
    q = tuple(mi())
    perm = list(permutations(range(1, n+1))) 
    num_p = perm.index(p)
    num_q = perm.index(q)
    print(abs(num_p - num_q))
    

if __name__ == "__main__":
    main()

Solution (Python):
from itertools import permutations

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

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

Solution (Python):
N= int(input())
p = input().replace(" ","")
q = input().replace(" ","")
kai = [1]
for i in range(2,N):
    kai.append(kai[-1]*i)
def calc(s,N):
    count =0
    nlist = [str(i) for i in range(1,N+1)]
    for i in range(N-1):
        
        idx = nlist.index(s[i])
        nlist.remove(s[i])
        count += (idx)*(kai[len(nlist)-1])
        
    return count+1

print(abs(calc(p,N)-abs(calc(q,N))))

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

a = list()
for i in range(1,n+1):
    a.append(int(i))
b = copy.copy(a)

kai = 1
for i in range(1,n+1):
    kai = kai * i

pans = 0
qans = 0
for i in range(n):
    kai = kai / (n-i)
    pans +=  kai * ( a.index(p[i]) + 1 )
    a.remove(p[i])
    
    qans +=  kai * ( b.index(q[i]) + 1 )
    b.remove(q[i])

print(int(abs(pans - qans)))

Solution (Python):
def yu(a):
    n = len(a)
    used = [False for i in range(n)]
    fact = 1
    ans = 0
    for i, x in enumerate(a[::-1]):
        cur = 0
        for y in range(x):
            if used[y]:
                cur += 1
        ans += cur * fact
        fact *= (i + 1)
        used[x-1] = True
    return ans
        

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(abs(yu(a) - yu(b)))

Solution (Python):
import itertools

N = int(input())
P = list(map(int, input().split(" ")))
Q = list(map(int, input().split(" ")))
a, b = 0, 0

for i, perm in enumerate(itertools.permutations(range(N))):
    if all([p1 == (p2 + 1) for p1, p2 in zip(P, perm)]):
        a = i
    if all([p1 == (p2 + 1) for p1, p2 in zip(Q, perm)]):
        b = i

print(abs(a - b))

Solution (Python):
from collections import deque
from collections import Counter
from itertools import product, permutations,combinations
from operator import itemgetter
from heapq import heappop, heappush
from bisect import bisect_left, bisect_right, bisect




from fractions import gcd
from math import ceil,floor, sqrt, cos, sin, pi, factorial
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**8)
INF = float('inf')
from datetime import datetime as dt

def main():
  n = int(input())
  p = tuple(map(int, input().split()))
  q = tuple(map(int, input().split()))
  l = [i for i in range(1,n+1)]
  for i, junretsu in enumerate(permutations(l, n)):
    if junretsu==p:
      a = i
    if junretsu==q:
      b=i
  print(abs(b-a))
  
  
if __name__ == '__main__':
  main()

Solution (Python):
import itertools
n = int(input())
p = tuple(int(i) for i in input().split())
q = tuple(int(i) for i in input().split())
a = tuple(itertools.permutations(list(range(1, n+1)), n))
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()))

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

num1=(y.index(P))
num2=(y.index(Q))

print(abs(num1-num2))

Solution (Python):
from itertools import permutations

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

dict_order = sorted(a)
pi = dict_order.index(tuple(p))
qi = dict_order.index(tuple(q))

print(abs(pi - qi))

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


count = 0
a, b = 0, 0
for index, i in enumerate(permutations(range(1, n+1))):
    if i in [P, Q]:
        if count == 0:
            count += 1
            a = index
        else:
            b = index
            break
if P != Q:
    print(abs(a - b))
else:
    print(0)

Solution (Python):
import sys
import itertools

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
P = tuple(lr())
Q = tuple(lr())
a = -1; b = -1
for i, x in enumerate(itertools.permutations(range(1, N+1), N)):
    if x == P:
        a = i
    if x == Q:
        b = i

answer = abs(a-b)
print(answer)

Solution (Python):
from itertools import permutations
from bisect import bisect_left

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

permutation = list(permutations(range(1, n+1)))
a = bisect_left(permutation, p)
b = bisect_left(permutation, q)

print(abs(a - b))

Solution (Python):

import sys
import itertools


def solve(N: int, P: "List[int]", Q: "List[int]"):
    index = 0
    p = -1
    q = -1
    P = tuple(P)
    Q = tuple(Q)
    for perm in itertools.permutations(range(1, N+1)):
        if perm == P:
            p = index
        if perm == Q:
            q = index
        index += 1
    print(abs(p-q))
    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 math
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
arr=[i for i in range(1,n+1)]
res_p=0
for i in range(n-1):
  res_p+=math.factorial(n-i-1)*(arr.index(p[i]))
  arr.remove(p[i])
arr=[i for i in range(1,n+1)]
res_q=0
for i in range(n-1):
  res_q+=math.factorial(n-i-1)*(arr.index(q[i]))
  arr.remove(q[i])
print(abs(res_p-res_q))

Solution (Python):
from itertools import *
A = list(permutations(range(1,1+int(input()))))
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
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()))
num_list=list(itertools.permutations(range(1,n+1)))

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

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

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

Solution (Python):
import math
import itertools

N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
P=tuple(P)
Q=tuple(Q)
n=[]
for i in range(N):
    n.append(i+1)
nn=list(itertools.permutations(n))

a=nn.index(P)+1
b=nn.index(Q)+1
print(abs(a-b))

Solution (Python):
import itertools

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

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

for i in range(len(c)):
    if(list(c[i]) == P):
        a = i+1
    if(list(c[i]) == Q):
        b = i+1
print(abs(a-b))

Solution (Python):

BIT = [0] * 20
frac = [1] * 20
ckn = [[0] * 20] * 20
maxN = 10
ans = [0] * 2


def upd(pos, val) :
    i = pos
    while i <= maxN:
        BIT[i] += val
        i += (i & (-i))
def get(pos):
    res = 0
    i = pos
    while i > 0:
        res += BIT[i]
        i -= (i & (-i))
    return res

def prepare():
    for i in range(1, maxN): frac[i] = frac[i - 1] * i
    for i in range(0, maxN):
        ckn[0][i] = 1
    for i in range(1, maxN):
        for j in range(i, maxN):
            ckn[i][j] = ckn[i - 1][j - 1] + ckn[i][j - 1]


prepare()
n = int(input())

for i in range(0, 2):
    for j in range(0, maxN): BIT[j] = 0
    s = input()

    for j in range(0, n) :
        x = int(s.split()[j])
        ans[i] += (x - 1 - get(x)) * frac[n - j - 1]
        upd(x, 1)

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

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

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

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

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

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

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

Solution (Python):
import itertools

n = int(input())
pl = tuple([int(i) for i in input().split()])
ql = tuple([int(i) for i in input().split()])

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

print(abs(all_list.index(pl) - all_list.index(ql)))

Solution (Python):
import itertools
N = int(input())
l = [i+1 for i in range(N)]
cnt = 0
l = list(itertools.permutations(l))
li = []
for i in l:
  li.append(list(i))
p_l = list(map(int,input().split()))
q_l = list(map(int,input().split()))

print(abs(li.index(q_l) -li.index(p_l)))

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

Solution (Python):
import sys
input=sys.stdin.readline
n=int(input())
p=tuple(map(int,input().split()))
q=tuple(map(int,input().split()))
l=[]
for i in range(n):
    l.append(i+1)
import itertools
c=1
for v in itertools.permutations(l,n):
    if p==v:
        pc=c
    if q==v:
        qc=c
    c+=1
print(abs(pc-qc))

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

Solution (Python):

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

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

Solution (Python):
x = int(input())
l1 = tuple(map(int,input().split()))
l2 = tuple(map(int,input().split()))
li =[]
for i in l1:
    li.append(i)
li.sort()
from collections import defaultdict
dd = defaultdict(int)
from itertools import product, permutations,combinations
c = 1
for i in permutations(li,x):
    dd[i] = c
    c += 1
print(abs(dd[l1]-dd[l2]))

Solution (Python):
import math

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

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

ord1 = 0
flag = [0] * (n+1)
for i in range(n-1):
	ln = 0

	for c in range(1,p[i]):
		if flag[c] == 0:
			ln = ln + 1 
	flag[p[i]] = 1
	ord1 = ord1 + ln * math.factorial(n-1-i)

ord1 = ord1+1 

  
ord2 = 0
flag = [0] * (n+1)
for i in range(n-1):
	ln = 0

	for c in range(1,q[i]):
		if flag[c] == 0:
			ln = ln + 1 
	flag[q[i]] = 1
	ord2 = ord2 + ln * math.factorial(n-1-i)

ord2 = ord2+1 


print(abs(ord2 - ord1))

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

Solution (Python):

import math
import itertools
import statistics

import collections

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
s = []
for i in range(1,n+1):
    s.append(i)

l = list(itertools.permutations(s, n))
l.sort()

start = -1
end = -1
for i in range(len(l)):
    if l[i]==tuple(p):
        start = i+1
    if l[i]==tuple(q):
        end = i+1

print(abs(end-start))

Solution (Python):
import itertools

n = int(input())
p_li = tuple(map(int,input().split()))
q_li = tuple(map(int,input().split()))

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

check_li = []

for number in permutations_number:
    check_li += [number]

check_li.sort()

position_1 = 0
position_2 = 0

for x in range(len(check_li)):
    if check_li[x] == p_li:
        position_1 = x
    if check_li[x] == q_li:
        position_2 = x
        
print(abs(position_1 - position_2))

Solution (Python):
import itertools
n=int(input())
numbers1k=[]
numbers2k=[]
s=[]
for i in range(n):
    s.append(i+1)
p=itertools.permutations(s,n)
u=list(p)

numbers1=input().rstrip().split(" ")
for num1 in numbers1:
    numbers1k.append(int(num1))
numbers2=input().rstrip().split(" ")
for num2 in numbers2:
    numbers2k.append(int(num2))
com1=tuple(numbers1k)
com2=tuple(numbers2k)
for i in range(len(u)):
    if u[i]==com1:
        a=i+1
for j in range(len(u)):
    if u[j]==com2:
        b=j+1


print(abs(b-a))

Solution (Python):
from itertools import permutations
import math

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

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


B = []
for i in permutations(A,N):
    B.append(list(i))


a = b = 0
for i in range(len(B)):
    if P == Q:
        break
    elif B[i] == P:
        a = i
    elif B[i] == Q:
        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()))

for idx, perm in enumerate(permutations(range(1, n+1))):
    
    res = True
    for ip in range(n):
        if p[ip] != perm[ip]:
            res = False
    if res:
        idx_p = idx
    res = True
    for iq in range(n):
        if q[iq] != perm[iq]:
            res = False
    if res:
        idx_q = idx

print(abs(idx_p - idx_q))

Solution (Python):




import itertools

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

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

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

print(abs(a-b))

Solution (Python):
import itertools

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

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


for pos, v in enumerate(itertools.permutations(gen)):
    for i, comp in enumerate(v):
        if P[i] == comp:
            continue
        else:
            break
    else:
        Pp = pos + 1

    for i, comp in enumerate(v):
        if Q[i] == comp:
            continue
        else:
            break
    else:
        Qp = pos + 1

print(abs(Pp - Qp))

Solution (Python):
from itertools import permutations

n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
a = list(permutations(range(1, n + 1)))
print(abs(a.index(p) - a.index(q)))

Solution (Python):
import itertools
import math


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

check = list(itertools.permutations(range(1,N+1)))
N_fac = math.factorial(N)

n1 = 0
n2 = 0
countP = 0
countQ = 0
for i in range(0,N_fac):
  for j in range(0,N):
    if(check[i][j] == P[j]):
      countP += 1
      if(countP == N):
        n1 = i
    if(check[i][j] == Q[j]):
      countQ += 1
      if(countQ == N):
        n2 = i
  countP = 0
  countQ = 0
        
num = n1-n2
print(abs(num))

Solution (Python):
from itertools import permutations
import math

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

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

lst = []
lstn = ['1', '2', '3', '4', '5', '6', '7', '8']

for i in permutations(lstn[:N]):
    lst.append(int(''.join(i)))
lst.sort()

for i in range(0, math.factorial(N)):
    if lst[i] == np: np = i
    if lst[i] == nq: nq = i

print(abs(np - nq))

Solution (Python):
from itertools import permutations as perm

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

for i in range(len(test)):
    if test[i] == P:
        a = i
    if test[i] == Q:
        b = i

print(abs(a-b))

Solution (Python):
import itertools

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


n_list = list(range(1, n+1))
n_perm = list(itertools.permutations(n_list))

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

Solution (Python):
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
cntp = 0
cntq = 0
ALL = list(itertools.permutations(range(1, N+1), N))

for i in range(len(ALL)):
    if ALL[i]==P:
        break
    elif ALL[i]!=P:
        cntp += 1
for i in range(len(ALL)):
    if ALL[i]==Q:
        break
    elif ALL[i]!=Q:
        cntq += 1

print(abs(cntq-cntp))

Solution (Python):


import itertools

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

    A = [i for i in range(1, N+1)]
    S = set()
    a = 0
    b = 0
    for i, permutated in enumerate(itertools.permutations(A)):
        if permutated == P:
            a = i
        if permutated == Q:
            b = i

    print(abs(a-b))

Solution (Python):
import itertools
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
i=0
for x in itertools.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


def main():
    length = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))

    permutation_li = list(permutations([i for i in range(1, length + 1)]))

    p_index = permutation_li.index(p)
    q_index = permutation_li.index(q)

    print(abs(p_index - q_index))


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

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

Solution (Python):
import math
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
visit = []
p_num = 1
q_num = 1
for i in range(n):
  visit.append(p[i])
  cnt = 0
  for j in range(p[i]):
    if j not in visit:
      cnt += 1
  p_num += math.factorial(n-i-1)*cnt
visit = []
for i in range(n):
  visit.append(q[i])
  cnt = 0
  for j in range(q[i]):
    if j not in visit:
      cnt += 1
  q_num += math.factorial(n-i-1)*cnt
print(abs(q_num-p_num))

Solution (Python):
from itertools import permutations
N = int(input())
P = input().replace(" ", "")
Q = input().replace(" ", "")

nums = []
for x in permutations(map(str, range(1, N + 1)), N):
    nums.append("".join(x))
nums.sort()
ans = abs(nums.index(Q) - nums.index(P))
print(ans)

Solution (Python):
import itertools
def resolve():
    N = int(input())
    P = tuple(map(int, input().split()))
    Q = tuple(map(int, input().split()))
    i, a, b = 0, 0, 0
    for p in itertools.permutations(range(1, N+1)):
        i += 1
        if P == Q:
            a = b = 0
            break
        elif p == P:
            a = i
        elif p == Q:
            b = i

    print(abs(a-b))

if __name__ == '__main__':
    resolve()

Solution (Python):
from itertools import permutations

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

p_index = 0
q_index = 0
for i, perm in enumerate(permutations(range(1, n+1))):
    if perm == p:
        p_index = i
    if perm == q:
        q_index = i
print(abs(p_index - q_index))

Solution (Python):
from itertools import permutations

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

p_index = 0
q_index = 0
for i, perm in enumerate(permutations(range(1, n+1))):
    if perm == p:
        p_index = i
    if perm == q:
        q_index = i
print(abs(p_index - q_index))