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 itertools

num = int(input())

kizyun = [i+1 for i in range(num)]

retu = list(itertools.permutations(kizyun, num))  

tansaku1 = input().split()
for i in range(len(tansaku1)):
  tansaku1[i] = int(tansaku1[i])
tansaku1 = tuple(tansaku1)

tansaku2 = input().split()
for i in range(len(tansaku2)):
  tansaku2[i] = int(tansaku2[i])
tansaku2 = tuple(tansaku2)

a = 0
b = 0

for i in range(len(retu)):
  if retu[i] == tansaku1:
    a = i+1
  if retu[i] == tansaku2:
    b = i+1

ans = abs(a-b)

print(ans)

Solution (Python):
import math

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
per = math.factorial(n - 1)
r = 0
r2 = 0
for k in range(1, n)[::-1]:
    t = p[0]
    c = sum([t > x for x in p])
    r += per * c
    p.remove(t)
    t = q[0]
    c = sum([t > x for x in q])
    r2 += per * c
    q.remove(t)
    per = int(per / k)

print(int(abs(r - r2)))

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

def DicNum(P,n): 
    count = 0
    for i in range(len(P)):
        if n < P[i]:
            count += 1
    return count

def DicNumP(P): 
    count = 0
    for i in range(len(P)):
        count += DicNum(P[i:],P[i])*math.factorial(N-i-1)
    return count

print(abs(DicNumP(P)-DicNumP(Q)))

Solution (Python):
import math

N = int(input())
A = 0
B = 0
a = list(map(int,input().split()))
b = list(map(int,input().split()))
a_num = [i+1 for i in range(N)]
b_num = [i+1 for i in range(N)]

for i in range(N):
    a_idx = a_num.index(a[i])
    b_idx = b_num.index(b[i])
    a_num.pop(a_idx)
    b_num.pop(b_idx)

    A = A + math.factorial(N-i)*((a_idx)/(N-i))
    B = B + math.factorial(N-i)*((b_idx)/(N-i))


print("{}".format(int(abs(A-B))))

Solution (Python):
import math
n = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
def f(l):
    return math.factorial(l)
a = 0
b = 0
R = [1,2,3,4,5,6,7,8,9]
S = [1,2,3,4,5,6,7,8,9]
for i in range(n):
    c = R.index(P[i])
    a += f(n-i-1)*(c-1)
    R.remove(P[i])
for i in range(n):
    d = S.index(Q[i])
    b += f(n-i-1)*(d-1)
    S.remove(Q[i])
print(abs(a-b))

Solution (Python):

import sys
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
from itertools import permutations

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

array = [item for item in range(1, n+1)]

for i, perm in enumerate(permutations(array)):
    if perm == p:
        frm = i
    if perm == q:
        to = i
print(abs(frm - to))

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

dict = {}
d = [i for i in range(1,n+1)]
i = 1
for x in permutations(d,n):
    dict[x] = i
    i += 1

print(abs(dict[P]-dict[Q]))

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

p_list = list(itertools.permutations(p, n))
p_list.sort()
a = p_list.index(p)
b = p_list.index(q)

print(abs(a-b))

Solution (Python):
import itertools


n = int(input())




p = input()
q = input()


i = 0



for x in itertools.permutations(range(1,n+1), n):
	
	x = " ".join(map(str,x))
	
	i += 1
	if x == p:
		a = i
		
	if x == q:
		b = i
		

print(abs(a-b))

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

Solution (Python):
import itertools
import numpy as np
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
count = 0
a = 0
b = 0
num = []
for i in range(1,n+1):
    num.append(i)
for balls in itertools.permutations(num):
    count = count + 1
    if(list(balls) == p):
         a = count
    if(list(balls) == q):
         b = count
print(np.abs(a-b))

Solution (Python):
import math

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

a = 0

for i, p in enumerate(P, start=1):
  for j in range(1, p):
    if not j in P[:i-1]:
    	a += math.factorial(N-i)
    
b = 0

for i, q in enumerate(Q, start=1):
  for j in range(1, q):
    if not j in Q[:i-1]:
      b	+= math.factorial(N-i)

sum = a - b
if sum < 0:
  sum *= -1

print(sum)

Solution (Python):
import math
 
def dic(s):
  l = len(s)
  if l == 0:
    return 0
  c = s[0]
  tmp = ((sorted(s)).index(c)-1) * math.factorial(l -1)
  return tmp + dic(s[1:])
 
n = input()
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))
 
print(abs(dic(s1)-dic(s2)))

Solution (Python):


import math

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

count =0
a=1
b=1
while(count<n):
    for i in r:
        if p[count] ==i :
            count+=1
            r.remove(i)
            break;
        else:
            a+=math.factorial(n-count-1)
r = [] 
for i in range(n):
    r.append(i+1)
count = 0
while(count<n):
    for i in r:
        if q[count] ==i :
            count+=1
            r.remove(i)
            break;
        else:
            b+=math.factorial(n-count-1)           
print(abs(a-b))

Solution (Python):
import itertools

total = int(input())
text_1 = list(map(int, input().split()))
text_2 = list(map(int, input().split()))
text_1_join = int("".join([str(x) for x in text_1]))
text_2_join = int("".join([str(x) for x in text_2]))

text_1_sort = sorted(text_1)
target = list(itertools.permutations(text_1_sort))
target_join = [int("".join(str(y) for y in x)) for x in target]

get_index_1 = target_join.index(text_1_join) + 1
get_index_2 = target_join.index(text_2_join) + 1

print(abs(get_index_1 - get_index_2))

Solution (Python):
import itertools
from math import factorial

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

count = 0
for i in range(f):
        if all[i] == P:
                count += i+1
        if all[i] == Q:
                count -= i+1

print(abs(count))

Solution (Python):



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


A=list(itertools.permutations(A))



M=1
for i in range(1,N+1):
    M*=i
for i in range(M):
    if A[i]==tuple(P):
        a=i+1
    if A[i]==tuple(Q):
        b=i+1
print(abs(b-a))

Solution (Python):
import itertools

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

for i, p in enumerate(itertools.permutations(range(1, N + 1))):
    if p == P:
        pi = i + 1
    if p == Q:
        qi = i + 1

print(abs(pi - qi))

Solution (Python):
import numpy as np
import math

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
enda = list([n+1])
endb = list([n+1])
numa = 0
numb = 0

for i in range(0,n-1):
  enda.append(a[i])
  endb.append(b[i])
  aa,bb = 0,0
  for j in range(0,i+1):
    if enda[j] < a[i]:
      aa += 1 
  a[i] = a[i] - aa
  for j in range(0,i+1):
    if endb[j] < b[i]:
      bb += 1
  b[i] = b[i] - bb
  
  numa += (a[i] -1) * math.factorial(n-1-i)
  numb += (b[i] -1) * math.factorial(n-1-i)

print(abs(numa - numb))

Solution (Python):

def insert_string_to_base(target_string, insert_point, insert_string):
    return target_string[:insert_point] + insert_string + target_string[insert_point:]

input1=input()
input2=input()
input3=input()

N=int(input1)

P=""
for i in range((len(input2)+1)//2):
    P+=input2[2*i]
Q=""
for i in range((len(input3)+1)//2):
    Q+=input3[2*i]



def permutate(n):
    ans=[]
    if n==1:
        ans=["1"]
    else:
        temp=permutate(n-1)

        for t in temp:
            for i in range(len(t)+1):
                tm=insert_string_to_base(t,i,"{}".format(n))
                ans.append(tm)

    return ans

arr=permutate(N)

ARR=sorted(arr)

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

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

Solution (Python):
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
N=[i for i in range(1,n+1)]
p1=[i for i in range(1,n+1)]
q1=[i for i in range(1,n+1)]
def kaijou(x):
    if x==0:
        return 0
    elif x==1:
        return 1
    elif x==2:
        return 2
    elif x==3:
        return 6
    elif x==4:
        return 24
    elif x==5:
        return 120
    elif x==6:
        return 720
    elif x==7:
        return 5040

s1=1
s2=1
j=1
for i in p:
    s1 += kaijou(n-j)*int(p1.index(i))
    j+=1
    p1.remove(i)
j=1
for i in q:
    s2 += kaijou(n-j)*int(q1.index(i))
    j+=1
    q1.remove(i)
k=s1-s2
if k<0:
    print(-k)
else:
    print(k)

Solution (Python):
def factlist(n):
  res = [1]
  for i in range(n):
    res.append(res[i] * (i+1))
  return res

def dic_ord(n, a):
  fact = factlist(n-1)
  b = list(range(1, n+1))
  res = 0
  for i in range(n-1):
    j = b.index(a[i])
    res += fact[n-i-1] * j
    b.pop(j)
  return res

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

print(abs(dic_ord(n, a)-dic_ord(n, b)))

Solution (Python):
import math
N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
def count(U):
    S = sorted(U)
    C = 1
    for i,j in enumerate(U):
        c = 0
        for u,v in enumerate(S):
            if v == j:
                del S[u]
                break
            else:
                c += 1
        C += (math.factorial(N-i-1))*c
    return C
print(abs(count(P)-count(Q)))

Solution (Python):
import math

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

ans_P = 0
for i in range(N):
    P_sort = sorted(P)
    a = P_sort.index(P[0])
    n = math.factorial(N-1-i)*a
    ans_P += n
    del P[0]

ans_Q = 0
for i in range(N):
    Q_sort = sorted(Q)
    a = Q_sort.index(Q[0])
    n = math.factorial(N-1-i)*a
    ans_Q += n
    del Q[0]

print(abs(ans_Q - ans_P))

Solution (Python):
def permutation(lst):
    
  if len(lst) == 0:
    return []

        
    
  if len(lst) == 1:
    return [lst]

        
    

  l = []  

    
  for i in range(len(lst)):
    m = lst[i]

        
        
    remLst = lst[:i] + lst[i + 1:]

        
        
    for p in permutation(remLst):
      l.append([m] + p)
  return l


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

NN = list(range(1, int(N) + 1))
P = permutation(NN)

xx = P.index(x)
yy = P.index(y)
print(abs(xx - yy))

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

    nlist = [i for i in range(1, N+1)]
    nlist2 = nlist.copy()
    NN = N
    NN -= 1
    tn = math.factorial(NN)
    a, b= 0, 0

    a += P[0] * tn - tn
    b += Q[0] * tn - tn
    nlist.remove(P[0])
    nlist2.remove(Q[0])

    for i in range(1, N):

        NN -= 1
        tn = math.factorial(NN)
        for j in range(len(nlist)):
            if P[i] == nlist[j]:
                nlist.remove(P[i])
                a+=j*tn - tn 
                break
        
        for j in range(len(nlist2)):
            if Q[i] == nlist2[j]:
                nlist2.remove(Q[i])
                b+=j*tn -tn
                break
    

    print(abs(a-b))

if __name__ == '__main__':
    main()

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

N = int(input())
P = tuple(input().split())
Q = tuple(input().split())
p_all = sorted(list(itertools.permutations(P, N)))
q_all = sorted(list(itertools.permutations(Q, N)))
p_in = p_all.index(P)
q_in = q_all.index(Q)
ans = abs(q_in - p_in)
print(ans)

Solution (Python):
import math

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

p = 0
q = 0

for i in range(N-1):
	tmp = 0
	n = P.pop(0)
	for x in range(N):
		if not (x+1 in P) and x+1 < n : tmp += 1
	p += (n-tmp-1) * math.factorial(N-(i+1))
	
	tmp = 0
	n = Q.pop(0)
	for x in range(N):
		if not (x+1 in Q) and x+1 < n : tmp += 1
	q += (n-tmp-1) * math.factorial(N-(i+1))

print(abs(p-q))

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy,copy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
    n = INT()
    p = LIST()
    q = LIST()
    li = list(permutations(range(1, n+1)))
    print(abs(li.index(tuple(p))-li.index(tuple(q))))

if __name__=='__main__':
    main()

Solution (Python):
def kai(x):
	ans = 1
	i=1
	while x>=i:
		ans = ans*i
		i+=1
	return ans
	

def calc(x, l):
	y=len(l)
	a=l[x]
	cnt = 0
	x+=1
	while x < y:
		if l[x] < a:
			cnt+= 1
		x+=1
	return(cnt)

n=int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
p_num=0
q_num=0
for i in range(n):
	p_num += kai(n-i-1)*calc(i,p)
	q_num += kai(n-i-1)*calc(i,q)
	
if p_num < q_num:
	t=p_num
	p_num = q_num
	q_num = t
		
print(p_num-q_num)

Solution (Python):
import itertools

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

count=1
for i in itertools.permutations(range(1,n+1)):
    if i == p_list:
        num1 = count
    if i == q_list:
        num2 = count
    count += 1

if num1 - num2 <0:
    print (num2-num1)
else:
    print (num1-num2)

Solution (Python):
def calc_order(nums):
  n = len(nums)
  order = 1
  ls = sorted(nums)
  for i, v in enumerate(nums[:-1]):
    c = (ls.index(v) - 1) * level_mat(n) // level_mat(n, i+1)
    order += c
    ls.remove(v)
  return order


def level_mat(n, m=None):
  if m is None:
    m = n
  assert n >= m

  if m == 0:
    return 1
  if n == 1:
    return 1
  else:
    return n * level_mat(n-1, m-1)


if __name__ == '__main__':
  n = int(input())
  ps = [int(i) for i in input().split()]
  qs = [int(i) for i in input().split()]
  print(abs(calc_order(ps) - calc_order(qs)))

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

def factrial(n):
  if n==0:
    return 1
  else:
    return(n * factrial(n-1))

def f(a):
  rank = 0
  for i in range(n-1):  
    left=a[i]-1
    for j in range(i+1):
      if a[j]<a[i]:
        left-=1    
    rank += left * factrial(n-i-1)  
  return rank

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

Solution (Python):
import itertools

n = int(input())
p = list(map(int, input().split()))
for i in range(len(p)):
	p[i] = p[i]-1
p = tuple(p)
q = list(map(int, input().split()))

a = list(itertools.permutations(range(n)))

for i in range(len(q)):
	q[i] = q[i]-1
q = tuple(q)
print(abs(a.index(p) - a.index(q)))

Solution (Python):
import itertools

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

for i in range(n):
    seq.append(i+1)

permutation = list(itertools.permutations(seq))



for i in range(len(permutation)):
    for j in range(n):
        if(p[j] != permutation[i][j]):
            
            
            break
        if(j == n-1):
            a = count
    for k in range(n):
        if(q[k] != permutation[i][k]):
            break
        if(k == n-1):
            b = count
    count = count + 1



print(abs(b-a))

Solution (Python):
import math

def getPosition(Num, n, i):
    Num_buff = Num[i:]
    
    Num_buff.sort()
    return Num_buff.index(n)



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

a = 0
b = 0





for i in range(N):
    a += (getPosition(P, P[i], i))*math.factorial(N-(i+1)) 
    b += (getPosition(Q, Q[i], i))*math.factorial(N-(i+1)) 
a += 1
b += 1
if a > b:
    print(a-b)
else:
    print(b-a)

Solution (Python):
import math
N = int(input())
H = list(map(int, input().split()))
A = list(map(int, input().split()))
ans = 0
h=0
a=0
L=[]
for i in range(1,N+1):
    L.append(i)

for i in range(N):
    for j in range(N-i):
        if(H[i]==L[j]):
            c=j

    h = h + math.factorial(N-1-i)*(c-1)
    L.remove(H[i])
for i in range(1,N+1):
    L.append(i)
for i in range(N):
    for j in range(N-i):
        if(A[i]==L[j]):
            c=j

    a = a + math.factorial(N-1-i)*(c-1)
    L.remove(A[i])
ans=h-a
if ans<0:
    ans = ans*(-1)
print(ans)

Solution (Python):
import itertools
a = int(input())
j = 1
b = []
c = []

num1 = input().split()
num2 = input().split()
for i in range(0, len(num1)): 
    num1[i] = int(num1[i])
for i in range(0, len(num2)): 
    num2[i] = int(num2[i]) 

if(a>=2 and a<=8):
  while (j<=a):
      b.append(j)
      j = j+1

c = list(itertools.permutations(b))
index1 = c.index(tuple(num1))
index2 = c.index(tuple(num2))
res = index1-index2 
if(res<0):
    print(res*(-1))
else:
    print(res)

Solution (Python):
import itertools
import math
n=int(input())
N=math.factorial(n)
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
l=list(itertools.permutations(range(1,n+1)))
for i in range(N):
    if l[i] == P:
        a = i
for j in range(N):
    if l[j] == Q:
        b = j
print(abs(b-a))

Solution (Python):
import math

n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
ansp = 0
ansq = 0
for i in range(n):
    ansp += (p[i]-1)*(math.factorial(n-i-1))
    
    
    for j in range(i+1,n):
        if p[j] > p[i]:
            p[j] -= 1
for i in range(n):
    ansq += (q[i]-1)*(math.factorial(n-i-1))
    for j in range(i+1,n):
        if q[j] > q[i]:
            q[j] -= 1

print(abs(ansp-ansq))

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

def kaijo(n):
  if n <= 0:
    return 0
  else:
    ret = 1
    for i in range(n):
      ret *= (i+1)
    return ret

num_p, num_q = 0, 0
done = []
for i in range(N):
  num = 0
  for j in range(len(done)):
    if done[j] < P[i]:
      num += 1
    else:
      pass
  
  num_p += kaijo(N-(i+1)) * (P[i] - num)
  done.append(P[i])

done = []
for i in range(N):
  num = 0
  for j in range(len(done)):
    if done[j] < Q[i]:
      num += 1
    else:
      pass
  num_q += kaijo(N-(i+1)) * (Q[i] - num)
  done.append(Q[i])

print(abs(num_p - num_q))

Solution (Python):
import itertools

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

DICT_NUM = sorted(itertools.permutations(P))

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

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

def kaijou(n):
    x = 1
    for i in range (1,n+1):
        x *= i
    return x

kaijou_ls = [0]*N

for i in range(N):
    kaijou_ls[i] = kaijou(i+1)


def count_order(A,k):
    if k==1:
        return 1
    else:
        B = A[N-k:]
        b = B[0]
        C = B.copy()
        C.sort()
        order = C.index(b)*kaijou_ls[k-2]

        return order+count_order(A,k-1)

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

Solution (Python):
import math
import itertools

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

p_list = [int(i) for i in P.split(" ")]
q_list = [int(i) for i in Q.split(" ")]

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

p_num = 1
q_num = 1
for i in itertools.permutations(n):
    if list(i)==p_list:
        a = p_num
    if list(i)==q_list:
        b = q_num
    p_num += 1
    q_num += 1

print(abs(a-b))

Solution (Python):
import itertools

in1 = int(input())
in2 = [input().strip().rsplit(" ") for i in range(2)]
count = 0 
for i in itertools.permutations(range(1, in1+1)):
    if in2[0] == list(map(str, i)):
      ans1 = count
    if in2[1] == list(map(str, i)):
      ans2 = count

    count += 1

print(abs(ans2 - ans1))

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

index = 0
for i in itertools.permutations(range(1,n+1)):
 if p == i:
  a = index
 if q == i:
  b = index
 index += 1

print(abs(a-b))

Solution (Python):
import itertools

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

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

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

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

import itertools
l = list(itertools.permutations(list(range(1, N+1))))
a = l.index(tuple(P))
b = l.index(tuple(Q))
print(abs(a-b))

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



R = []
for i in range(N):


    R.append( i+1 ) 




import itertools
cnt = 1
for v in itertools.permutations(R, N): 

    if list(v) == P: 
       Porder = cnt
    if list(v) == Q: 
       Qorder = cnt
    cnt += 1


sol = abs(Qorder-Porder)
print(sol)

Solution (Python):
import math

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

def judgement(n, pos):
    return (int(pos) - 1) * math.factorial(n - 1)

def position(target, list):
    pos = 0
    for i in list:
        if (int(target) > int(i)):
            pos += 1
    return pos + 1

def calculateRank(list):
    targetNum = 0
    rank = 0
    for i in range(N - 1):
        targetNum = list[0]
        list.pop(0)
        targetPosition = position(targetNum, list)
        rank += judgement(N - i, targetPosition)

    return rank

rankA = calculateRank(P)
rankB = calculateRank(Q)

print(abs(rankA - rankB))

Solution (Python):
n = int(input())
p = [i for i in map(int, input().split())]
q = [i for i in map(int, input().split())]

sorted_list = sorted(p)
all_list = []

def listExcludedIndices(data, indices=[]):
	return [x for i, x in enumerate(data) if i not in indices]

def permutationListRecursive(data, r):
	if r <= 0 or r > len(data):
		return []
	
	result = []
	_permutationListRecursive(data, r, [], result)
	return result

def _permutationListRecursive(data, r, progress, result):
	if r == 0:
		result.append(progress)
		return
	
	for i in range(len(data)):
		_permutationListRecursive(listExcludedIndices(data, [i]), r - 1, progress + [data[i]], result)


a = -1
b = -1

for i, list_ in enumerate(permutationListRecursive(sorted_list, n)):
	
	if list_ == p:
		a = i

	if list_ == q:
		b = i

	if a != -1 and b != -1:
		break

print(abs(a-b))

Solution (Python):
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
from itertools import permutations
X = permutations(list(range(1, N+1)))
for i, x in enumerate(X):
    x = list(x)
    if x == P:
        p = i
    if x == Q:
        q = i
print(abs(p-q))

Solution (Python):
import itertools
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
list_a = list(range(1,N+1))
tuple_a = tuple(list_a)
ptr = list(itertools.permutations(tuple_a))
ptr_num = len(list(itertools.permutations(tuple_a)))
for i in range(0,ptr_num):
  if ptr[i] == tuple(P):
    P_num=i+1
  if ptr[i] == tuple(Q):
    Q_num=i+1
print(abs(P_num-Q_num))

Solution (Python):
N = int(input())
p = tuple(int(x) for x in input().split())
q = tuple(int(x) for x in input().split())
r = []
a=0
c1 =0
c2 =0
import itertools

def for_factorial(n):
    val = 1
    for i in range(2, n + 1):
        val *= i
    return val

a =for_factorial(N)

r =list(itertools.permutations(range(1,N+1)))
for i in range(a):
    if p == r[i]:
        c1 = i+1

for i in range(a):
    if q == r[i]:
        c2 = i+1

if c1 >= c2:
    print(c1-c2)
else:
    print(c2-c1)

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

import math
import itertools

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

for i in range(len(dia)):
    if list(dia[i]) == p:
        sc_p = i
    if list(dia[i]) == q:
        sc_q = i

print(abs(sc_p - sc_q))

Solution (Python):
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
junretsu = sorted(set(itertools.permutations( P )))


count = 1
a = 0
for x in junretsu:
    if(list(x) == P):
        a = count
    count += 1

count = 1
b = 0
for x in junretsu:
    if(list(x) == Q):
        b= count
    count += 1

print(abs(b-a))

Solution (Python):

"""
Created on Fri Jan 10 21:13:02 2020

@author: masat
"""
import math

N = int(input())
P_list = list(map(int, input().split()))
Q_list = list(map(int, input().split()))

def jishojun(a_list):
    dist = 0
    for i in range(N):
        sorted_slice = sorted(a_list[i:])
        dist += math.factorial(N-i-1) * sorted_slice.index(a_list[i])
    return dist

answer = abs(jishojun(P_list) - jishojun(Q_list))
print(answer)

Solution (Python):
import itertools

N = int(input())
P = str(input()).split(" ")
Q = str(input()).split(" ")


All = []

for i in itertools.permutations(P):
    stack = ""
    for j in i :
        stack = stack + j
    All.append(int(stack))

All.sort()


stack = ""
for i in P:
    stack = stack + i
P = int(stack)

stack = ""
for i in Q:
    stack = stack + i
Q = int(stack)


P = All.index(P)+1
Q = All.index(Q)+1

print(abs(P-Q))

Solution (Python):
import itertools
import math

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

N_l = list(itertools.permutations(P_org))
N_fac = math.factorial(N)

a = 1
b = 1
for x in range(N_fac):
    if (P == list(N_l[x])):
        a += x
    if (Q == list(N_l[x])):
        b += x    
        
print(abs(a-b))

Solution (Python):
import itertools

i = int(input())
P = input().split()
Q = input().split()

list_to_permute = []
for each in range(1, i+1):
    list_to_permute.append(each)

list_of_all_permutes = list(itertools.permutations(list_to_permute))



P = tuple(int(element) for element in P)
Q = tuple(int(element) for element in Q)
a = list_of_all_permutes.index(P) + 1
b = list_of_all_permutes.index(Q) + 1 

print(abs(a-b))

Solution (Python):
import numpy as np
import itertools
from sys import stdin
lines = stdin.readlines()
 
N = int(lines[0])
P = list(map(str, lines[1].split()))
Q = list(map(str, lines[2].split()))

permu = []
for a in range(N):
  permu.append(str(a + 1))



cnt_a = 1
for p in itertools.permutations(permu):
  cnt_a += 1
  p_act = np.array(p)
  p_test = np.array(P)
  if (p_test == p_act).all() == True:
    a = cnt_a

cnt_b = 1
for q in itertools.permutations(permu):
  cnt_b += 1
  q_act = np.array(q)
  q_test = np.array(Q)
  if (q_test == q_act).all() == True:
    b = cnt_b

print(abs(a - b))

Solution (Python):
import math
N=int(input())
P=list(map(int, input().split()))
Q=list(map(int, input().split()))
a=b=1
l=[i for i in range(1,N+1)]
m=[i for i in range(1,N+1)]
for i in range(N):
  
  
  if N-i-1 < 0:
    pass
  else:
    a += l.index(P[i])*math.factorial(N-i-1)
  
  if not i==N-1:
    l.pop(l.index(P[i]))
for i in range(N):
  if N-i-1 < 0:
    pass
  else:
    b += m.index(Q[i])*math.factorial(N-i-1)
  if not i==N-1:
    m.pop(m.index(Q[i]))
print(abs(a-b))

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


n = N - 1
num_list = [i+1 for i in range(N)]

num_list_set = list(itertools.permutations(num_list))
a = num_list_set.index(P)
b = num_list_set.index(Q)

print(abs(a-b))

Solution (Python):
import math

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

def count_dict(N, P):
  sum_p = 1
  count = 0
  for p in P[:-1]:
    P_rest = sorted(P[count:])
    p_order = P_rest.index(p)
    sum_p += (p_order) * math.factorial(N-count-1)
    count += 1
  return sum_p

a = count_dict(N, P)
b = count_dict(N, Q)

print(abs(a-b))

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

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

ls = [1,1,2,6,24,120,720,5040,40320]

p_copy = p.copy()
q_copy = q.copy()

def mycalc(ls,th):
    ans = [ i for i in ls if i<th ]
    return ans

ans = mycalc(p,7)

a = 0
for i in range(n-2):
    p_copy.remove(p[i])
    g = mycalc(p_copy,p[i])
    a += (len(g))*ls[n-i-1]
if p_copy[0]<p_copy[1]:
    a += 1
else:
    a += 2

r = list(range(1,n+1))
b = 0
for i in range(n-2):
    q_copy.remove(q[i])
    g = mycalc(q_copy,q[i])
    b += (len(g))*ls[n-i-1]
if q_copy[0]<q_copy[1]:
    b += 1
else:
    b += 2

print(abs(a-b))

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

Solution (Python):
def kaijou(n):
  result = 1
  for i in range(1, n+1):
    result *= i
  return result

def nanbanme(l, n):
  for i in range(len(l)):
    if l[i] == n:
      return i
  
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
p_n = [i for i in range(1, n+1)]
q_n = [i for i in range(1, n+1)]

pp, qq = 1, 1

for i in range(n):
  if p[i] != min(p_n):
    pp += kaijou(n-i-1) * nanbanme(p_n, p[i])
  p_n.remove(p[i])
    
  if q[i] != min(q_n):
    qq += kaijou(n-i-1) * nanbanme(q_n, q[i])
  q_n.remove(q[i])
    
print(abs(pp-qq))

Solution (Python):
import itertools
N = int(input())
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))
cnt = 0
cnt2 = 0
for i in itertools.permutations(range(1,N+1)):
  if a == i:
    break
  cnt += 1
for s in itertools.permutations(range(1,N+1)):
  if b == s:
    break
  cnt2 += 1
print(abs(cnt-cnt2))