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



Sample input:
3
1 3 2
3 1 2


Sample output:
3

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
li = [i for i in range(1, n+1)]
j = 1
p_index = 1
q_index = 1
for v in itertools.permutations(li, n):
  if(list(v) == p):
    p_index = j
  if(list(v) == q):
    q_index = j
  j += 1
print(abs(p_index - q_index))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
l = [list(v) for v in itertools.permutations(range(1, n + 1))]

p = list(map(int, input().split()))
p_index = l.index(p)

q = list(map(int, input().split()))
q_index = l.index(q)

print(abs(p_index - q_index))

Submission status: Accepted

Solution code:
import itertools

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

lst = [int(x) for x in P]
lst = sorted(itertools.permutations(lst))
print(abs(lst.index(P) - lst.index(S)))

Submission status: Accepted

Solution code:
import itertools
 
def resolve():
    N = int(input())
    P_list = tuple(map(int, input().split()))
    Q_list = tuple(map(int, input().split()))
 
    N_list = [(i+1) for i in range(N)]
    N_permutations_list = itertools.permutations(N_list)
 
    i = 1
    for i_list in N_permutations_list:
        if i_list == Q_list:
            a = i
        if i_list == P_list:
            b = i
        i += 1
 
    print(abs(a-b))
 
 
if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
import math
N = int(input())
P_list = [int(i) for i in input().split()]
Q_list = [int(i) for i in input().split()]
def dic_num(N, X_list):
    now_num = N
    ans = 0
    while len(X_list)>1:
        value = (X_list[0]-1)*math.factorial(now_num-1)
        ans += value
        now_num -= 1
        for i,n in enumerate(X_list):
            if n > X_list[0]:
                X_list[i]=X_list[i]-1
        X_list.pop(0)
    return ans
print(abs(dic_num(N, P_list)-dic_num(N, Q_list)))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


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

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

a = PERMUTATIONS.index(p) + 1
b = PERMUTATIONS.index(q) + 1

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

Submission status: Accepted

Solution code:
import itertools

n = int(input())
lst = [int(elem) for elem in range(1, n+1)]
p = list(itertools.permutations(lst))

ps = [int(elem) for elem in input().split()]
qs = [int(elem) for elem in input().split()]

print(abs(p.index(tuple(ps)) - p.index(tuple(qs))))

Submission status: Accepted

Solution code:
n=int(input())
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))
import itertools as it
x=0
y=0
for i,j in enumerate(it.permutations(list(range(1,n+1)))):
    if a==j:
        x=i
    if b==j:
        y=i
print(abs(x-y))

Submission status: Accepted

Solution code:
def dict_order(l): # l=list(1,...,nの順列)
    import math 
    n = len(l)
    order = 0 # lの辞書式順序の番号
    used = [0]*n
    for i in range(n):
        order += (l[i]-1-sum(used[:l[i]]))*math.factorial(N-1-i)
        used[l[i]-1] += 1
    return order # lの辞書式順序の番号
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
p = dict_order(P)
q = dict_order(Q)
print(abs(p-q))

Submission status: Accepted

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

d = []

def func(x):
    if len(x) == n:
        temp = 0
        for i, t in enumerate(x):
            temp += t * (n ** i)
        d.append(temp)
        return
    for i in range(1, n+1):
        if i not in x:
            func(x + [i])

func([])

d.sort()
p = list(reversed(p))
q = list(reversed(q))
a = 0
b = 0
for i in range(n):
    a += p[i] * (n ** i)
    b += q[i] * (n ** i)

#print(a, b, d)
print(abs(d.index(a) - d.index(b)))

Submission status: Accepted

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

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

def calc_index( list_of_number: list ):
	lists = list(range(1, n+1))
	ans = 1
	for i in range( 1, n ):
		index = lists.index( list_of_number[ i - 1 ] )
		ans += factorial( n - i ) * ( index )
		lists.remove( list_of_number[ i - 1 ] )
	return ans
ans_p = calc_index( p )
ans_q = calc_index( q )

print( abs( ans_p - ans_q ))

Submission status: Accepted

Solution code:
import itertools

def resolve():
    N = int(input())
    P_list = tuple(map(int, input().split()))
    Q_list = tuple(map(int, input().split()))

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

    i = 1
    for i_list in N_permutations_list:
        if i_list == Q_list:
            a = i
        if i_list == P_list:
            b = i
        i += 1

    print(abs(a-b))


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
from itertools import permutations

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

for idx, pm in enumerate(permutations(range(1, N + 1))):
    if P == pm:
        a = idx
    if Q == pm:
        b = idx

print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations

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

ps = permutations(range(1, N + 1))

try:
    x, y = [i for i, t in enumerate(ps) if t == P or t == Q]
except ValueError:
    print(0)
else:
    print(abs(x - y))

Submission status: Accepted

Solution code:
from itertools import permutations

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

ps = list(permutations(range(1, N + 1)))
ps.index(P)

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

Submission status: Accepted

Solution code:
import itertools

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

Submission status: Accepted

Solution code:
import itertools
n=int(input())
p=tuple(map(int,input().split()))
q=tuple(map(int,input().split()))
r=list(itertools.permutations(p))
r.sort()
count1=r.index(p)
count2=r.index(q)
print(abs(count1-count2))

Submission status: Accepted

Solution code:
import itertools
import numpy as np
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))

num = np.arange(1, n+1)

zyun = list(itertools.permutations(list(num), n))

for i in range(0, len(zyun)):
    if zyun[i] == p:
        a = i+1
    if zyun[i] == q:
        b = i+1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N = int(sys.stdin.buffer.readline())
P = tuple(map(int, sys.stdin.buffer.readline().split()))
Q = tuple(map(int, sys.stdin.buffer.readline().split()))

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

Submission status: Accepted

Solution code:
import itertools
N=int(input())
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
R=list(itertools.permutations(P))
R.sort()
count1=R.index(P)
count2=R.index(Q)
print(abs(count1-count2))

Submission status: Accepted

Solution code:
import itertools
a=int(input())
z=tuple(map(int,input().split()))
x=tuple(map(int,input().split()))
y=list(itertools.permutations(z))
y.sort()
ans1=y.index(z)+1
ans2=y.index(x)+1
print(abs(ans1-ans2))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = tuple([int(_) for _ in input().split()])
Q = tuple([int(_) for _ in input().split()])
n = [int(i) for i in range(1, N + 1)]
jun = list(itertools.permutations(n, N))

p = jun.index(P) + 1
q = jun.index(Q) + 1

print(abs(p - q))

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
from collections import deque
import re
import math
import functools
import itertools


def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29


def mk1d(n, val=INF):
    return [val for i in range(n)]

def mk2d(h, w, val=INF):
    return [[val for i in range(w)]for i in range(h)]

DIV = 998244353


def convolve(a, b):
    p, g = 1107296257, 5
    n0, n1 = len(a), len(b)
    n = 1 << (max(n0, n1) - 1).bit_length() + 1
    a = a + [0] * (n-n0)
    b = b + [0] * (n-n1)
    w = pow(g, (p - 1) // n, p)
    invw = pow(w, p-2, p)

    def fft(f):
        d = n // 2
        v = w
        while d >= 1:
            u = 1
            for i in range(d):
                for j in range(i, n, 2*d):
                    f[j], f[j+d] = (f[j] + f[j+d]) % p, u * (f[j] - f[j+d]) % p
                u = u * v % p
            v = v * v % p
            d //= 2

    def ifft(f):
        d = 1
        while d < n:
            v = pow(invw, n // (2 * d), p)
            u = 1
            for i in range(d):
                for j in range(i, n, 2*d):
                    f[j+d] *= u
                    f[j], f[j+d] = (f[j] + f[j+d]) % p, (f[j] - f[j+d]) % p
                u = u * v % p
            d *= 2

    fft(a), fft(b)
    for i in range(n):
        a[i] = a[i] * b[i] % p
    ifft(a)
    invn = pow(n, p - 2, p)
    return [a[i] * invn % p for i in range(n0 + n1 - 1)]


def main():
    N = iRaw()
    Ps = tuple(isRaw())
    Qs = tuple(isRaw())
    idxP = -1
    idxQ = -1
    permN = itertools.permutations(range(1,N+1),N)
    for idx,perm in enumerate(permN):
        if  idxP==-1 and perm == Ps:
            idxP = idx
        if idxQ == -1 and perm == Qs:
            idxQ = idx
    return abs(idxP-idxQ)

if __name__ == "__main__":
    print(main())

Submission status: Accepted

Solution code:
N=int(input())
L=[[int(x) for x in input().split()] for i in range(2)]
t=[0]*2

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

for i in range(2):
  o=n
  D=[x for x in range(1,N+1)]
  for j in range(N):
    o//=len(D)
    t[i]+=o*D.index(L[i][j])
    D.remove(L[i][j])

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

Submission status: Accepted

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

def make_val(suretsu):
    val = 0
    for index in range(n):
        val += suretsu[n - index - 1] * pow(10, index)
    return val

p_val = make_val(p)
q_val = make_val(q)
min_val = min(p_val, q_val)
max_val = max(p_val, q_val)

count = 0
counting = False
p_rank = 0
q_rank = 0
for suretsu in itertools.permutations(range(1, n+1)):
    val = make_val(suretsu)
    if val < p_val:
        p_rank += 1
    if val < q_val:
        q_rank += 1
    p_rank += 1
    q_rank += 1

print(abs(p_rank-q_rank))

Submission status: Accepted

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

def count_junretsu(retsu):
	# 大きさNの順列を辞書順に作成し、順番にP,Qと比較する
	for i,l in enumerate(itertools.permutations(range(1,N+1))):
		if retsu == list(l):
			return(i+1)

a = count_junretsu(P)
b = count_junretsu(Q)
print(abs(a-b))

Submission status: Accepted

Solution code:
import math
import itertools
n=int(input())

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

a_str = [''.join(v) for v in itertools.permutations(a)]
a_int = [int(i) for i in a_str]
a_int.sort()

x="".join(a)
y="".join(b)

p=a_int.index(int(x))+1
q=a_int.index(int(y))+1

print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools
# import sys

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


# print(N)

so = [x + 1 for x in range(N)]

# print(so)

a = 0
b = 0
count = 1
for v in itertools.permutations(so, N):
    if v == P:
        a = count

    if v == Q:
        b = count
    
    count = count + 1

print(abs(a - b))

Submission status: Accepted

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

for i,s in enumerate(l):
  if s==p:a=i
  if s==q:b=i
print(abs(a-b))

Submission status: Accepted

Solution code:
import sys

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

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
p=[]
for i in range(1,n+1):
    p.append(i)
a=list(map(int,input().split()))
b=list(map(int,input().split()))
perm=list(permutations(p))
for i in perm:
    if a==list(i):
        res=perm.index(i)
    if b==list(i):
        temp=perm.index(i)
print(abs(res-temp))

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N,num):
    if N<=0:
        return [[] for _ in range(num)]
    elif num==1:
        return [I() for _ in range(N)]
    else:
        read_all = [tuple(II()) for _ in range(N)]
        return map(list, zip(*read_all))

#################

from itertools import permutations

N = I()
P = tuple(III())
Q = tuple(III())

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

for i in range(len(A)):
    if A[i]==P:
        p = i
    if A[i]==Q:
        q = i

print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools

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

permutations = list(itertools.permutations(range(1, N + 1)))
a = permutations.index(P)
b = permutations.index(Q)

print(abs(a - b))

Submission status: Accepted

Solution code:
from itertools import permutations

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

P = []
for perm in permutations(range(1, N + 1), r=N):
    P.append(tuple(perm))

P.sort()
print(abs(P.index(A) - P.index(B)))

Submission status: Accepted

Solution code:
import itertools

N = int(input())

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

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

print(abs(R.index(tuple(P)) - R.index(tuple(Q))))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
for i, x in enumerate(itertools.permutations(range(1, N+1))):
    if x == P:
        p_idx = i
    if x == Q:
        q_idx = i
print(abs(p_idx - q_idx))

Submission status: Accepted

Solution code:
import math
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
pp = sorted(p)
qq = sorted(q)

x = 0
y = 0
l = 1
m = 1
for i in p[:n-1]:
    x += math.factorial(n-l)*pp.index(i)
    l += 1
    pp.remove(i)
    del p[0]
    
for j in q[:n]:
    y += math.factorial(n-m)*qq.index(j)
    m += 1
    qq.remove(j)
    del q[0]

print(abs((x+1)-(y+1)))

Submission status: Accepted

Solution code:
#C - Count Order
from itertools import permutations
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
l = list(range(1,N+1))
count = 0
ans_p = 0
ans_q = 0
for i in permutations(l):
    count += 1
#    print(i)
#    print(P)
    if i == P:
        ans_p = count
    else:
        pass
    if i == Q:
        ans_q = count
    else:
        pass
#print(ans_p,ans_q)
print(abs(ans_p - ans_q))

Submission status: Accepted

Solution code:
def main():
    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, l in enumerate(permutations(list(range(1,n+1)))):
        if p == l:
            a = i
        if q == l:
            b = i
        if a != 0 and b!= 0:
            break
    print(abs(a-b))
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math

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


def Order(n, s):
    cnt = 1
    num_list = []
    for i in range(n):
        num_list.append(i + 1)
    for i in range(n):
        index = num_list.index(s[i])
        cnt += index * math.factorial(n - i - 1)
        del num_list[index]

    return cnt


ans = Order(N, P) - Order(N, Q)
if ans < 0:
    ans *= -1
print(ans)

Submission status: Accepted

Solution code:
# C - Count Order

import itertools

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

perm = list(itertools.permutations(P))
perm.sort()

a = perm.index(tuple(P))
b = perm.index(tuple(Q))
print(abs(a - b))

Submission status: Accepted

Solution code:
import itertools
def main():
    n = int(input())
    p = tuple(map(int,input().split(' ')))
    q = tuple(map(int,input().split(' ')))
    for i,seq in enumerate(itertools.permutations(range(1,n+1))):
        if p==seq:
            a = i
        if q==seq:
            b = i
    print(abs(a-b))
    return 


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
from itertools import permutations
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
res = list(range(1, n + 1))
cnt = 0
for i in permutations(res):
    cnt += 1
    if i == p:
        p_tmp = cnt
    if i == q:
        q_tmp = cnt

print(abs(p_tmp - q_tmp))

Submission status: Accepted

Solution code:
n = int(input())
tp = tuple(map(int, input().split()))
tq = tuple(map(int, input().split()))

import itertools as it

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

print(abs(l.index(tp) - l.index(tq)))

Submission status: Accepted

Solution code:
import itertools
N=int(input())
P=tuple([int(i)-1 for i in input().split()])
Q=tuple([int(i)-1 for i in input().split()])
SEQ=sorted(list(itertools.permutations(range(N),N)))
#print(SEQ)

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

Submission status: Accepted

Solution code:
import itertools

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

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

for i, node in enumerate(all_pattern):
  #print(node)
  if node == P:
    p = i
  if node ==  Q:
    q = i
    
    
print(abs(p-q))

Submission status: Accepted

Solution code:
N=int(input())
P=list(map(int,input().split()))
ps=""
for i in range(N):
  ps+=str(P[i])
Q=list(map(int,input().split()))
qs=""
for i in range(N):
  qs+=str(Q[i])

stack=[]
stack.append("")
res=[]
while stack:
  d=stack.pop()
  if len(d)==N:
    res.append(d)
    continue
  for i in range(1,N+1):
    if str(i) not in d:
      stack.append(d+str(i))
  
res=res[::-1]
a=0
b=0
for i in range(len(res)):
  if res[i]==ps:
    a=i+1
  if res[i]==qs:
    b=i+1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
string = str(1)
for i in range(2, n + 1):
    string += str(i)

    
string_list = []    
a = tuple(input().split(" "))
b = tuple(input().split(" "))
for i in itertools.permutations(string):
    string_list.append(i)


for i,j in enumerate(string_list):
    if j == a:
        A = i + 1
    if j == b:
        B = i + 1
print(abs(A - B))

Submission status: Accepted

Solution code:
#python3
from itertools import permutations
n=int(input())
p=[int(i) for i in input().split()]
q=[int(i) for i in input().split()]

def f(lis):
  cnt=0
  for i in permutations(range(1,n+1)):
    cnt+=1
    if i == tuple(lis):
      return cnt

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

Submission status: Accepted

Solution code:
from itertools import permutations as perm
import sys
readline = sys.stdin.buffer.readline

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

p_lst = list(perm(list(range(1, n + 1)), n))  # 排列
pn = qn = 0
for i,j in enumerate(p_lst, 1):
  if p == j:
    pn = i
  if q == j:
    qn = i
  if pn * qn != 0:
    break
print(abs(pn - qn))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
T = list(range(1,N+1))
S = list(itertools.permutations(T, N))
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]

A = S.index(tuple(P))
B = S.index(tuple(Q))
print(abs(A-B))

Submission status: Accepted

Solution code:
def factorial(x):
    if x == 0:
        return 1
    else:
        return factorial(x-1)*x

n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
"""
2 3 1 4 5
1 2 5 4 3
Go from the lower to higher permutation
if it is starting from k then ord(p)
2 3 4 1 5
2 3 4 5 1
How to find the order of a permutation
new_lowest = 1
3
1 2 3 -- has to give me 1
1 3 2 -- has to give me 2
2 1 3 -- has to give me 3
2 3 1 -- has to give me 4
3 1 2 -- has to give me 5
3 2 1 -- has to give me 6
"""
total = n
order_p = 1
original = []
for i in range(1,n+1):
    original.append(i)
for term in p:
    order_p+=factorial(total-1)*(original.index(term))
    original.remove(term)
    total-=1

for i in range(1,n+1):
    original.append(i)
order_q=1
total=n
for term in q:
    order_q+=factorial(total-1)*(original.index(term))
    original.remove(term)
    total-=1
print(abs(order_p-order_q))

Submission status: Accepted

Solution code:
fact = [1]
for i in range(20):
    fact.append(fact[-1] * (i+1))

def calc(L):
    NN = 17
    BIT=[0]*(2**NN+1)
    def addbit(i):
        while i <= 2**NN:
            BIT[i] += 1
            i += i & (-i)
    def getsum(i):
        ret = 0
        while i != 0:
            ret += BIT[i]
            i -= i&(-i)
        return ret
    re = 0
    for i, a in enumerate(L[::-1]):
        re += getsum(a) * fact[i]
        addbit(a)
    return re

N = int(input())
P = [int(a) for a in input().split()]
Q = [int(a) for a in input().split()]
 
print(abs(calc(P) - calc(Q)))

Submission status: Accepted

Solution code:
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)
ans=[]
for j in itertools.permutations(a):
    ans.append(list(j))
print(abs(ans.index(P)-ans.index(Q)))

Submission status: Accepted

Solution code:
import itertools

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

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

for i, node in enumerate(all_pattern):
  if node == P:
    p = i
  if node ==  Q:
    q = i
    
    
print(abs(p-q))

Submission status: Accepted

Solution code:
from itertools import permutations

N=int(input())

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

Ps="".join(P)

Qs="".join(Q)

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

Per=list(permutations(li,N))
idxP=0
idxQ=0
for idx,x in enumerate(Per):
    temp="".join(x)
    if Ps==temp:
        idxP=idx+1
    if Qs==temp:
        idxQ=idx+1
    if  (idxP!=0 and idxQ!=0):
        break

print(abs(idxP-idxQ))

Submission status: Accepted

Solution code:
import math
from itertools import permutations
def generate_permutations(n):
    perms = permutations(range(1, n+1), n)
    return [perm for perm in perms]
 
n = int(input())
ptuple = tuple(map(int, input().split()))
qtuple = tuple(map(int, input().split()))
 
perms = generate_permutations(n)
a = perms.index(ptuple)
b = perms.index(qtuple)
print(int(math.fabs(a - b)))

Submission status: Accepted

Solution code:
import math
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
cp = 1
lp = n
for i in range(n):
  pi = p.pop(0)
  lp -= 1
  cp += (pi-1)*math.factorial(lp)
  for j in range(lp):
    if p[j] > pi:
      p[j] -= 1
cq = 1
lq = n
for i in range(n):
  qi = q.pop(0)
  lq -= 1
  cq += (qi-1)*math.factorial(lq)
  for j in range(lq):
    if q[j] > qi:
      q[j] -= 1
print(abs(cp-cq))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
perm = itertools.permutations(range(1, N+1), N)

cnt = 0
flg = 0
for p in perm:
  cnt = cnt + 1
  if p == P:
    cnt_P = cnt
    flg = flg + 1
  if p == Q:
    cnt_Q = cnt
    flg = flg + 1
  if flg == 2:
    break
print(abs(cnt_P - cnt_Q))

Submission status: Accepted

Solution code:
import itertools

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

per = list(itertools.permutations(lst))


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


s = per.index(a)
t = per.index(b)

ans = abs(s - t)
print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations

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

for i, Rs in enumerate(permutations(range(1, N+1)), 1):
    Rs = list(Rs)
    if Ps == Rs:
        a = i
    if Qs == Rs:
        b = i

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

o_p = 0
o_q = 0
count = 0
for i in itertools.permutations(range(1, n + 1)):
    count += 1
    if p == i:
        o_p = count
    if q == i:
        o_q = count
print(abs(o_p - o_q))

Submission status: Accepted

Solution code:
from itertools import permutations 

n = int(input())
p = tuple(int(i) for i in input().split())
q = tuple(int(i) for i in input().split())
a = 0
b = 0
cnt = 0
st = 0
for i in permutations(range(1,n+1)):
    cnt += 1
    if i == p:
        a = cnt
        st += 1
    if i == q:
        b = cnt
        st += 1
    if st == 2:
        break
    
print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations 

n = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
a = 0
b = 0
cnt = 0
st = 0
for i in permutations(range(1,n+1)):
    cnt += 1
    if list(i) == p:
        a = cnt
        st += 1
    if list(i) == q:
        b = cnt
        st += 1
    if st == 2:
        break
    
print(abs(a-b))

Submission status: Accepted

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

def kai(n):
  x = 1
  i = 1
  while i <= n:
    x *= i
    i += 1
  return x

#print(kai(5))

def number(X):#Xの辞書順を求める関数
  N = len(X)
  s = 1
  num_list = [1] * N#0,1,2,3,4,5..に対応
  for i in range(N):
    x = X[i]
    sub = sum(num_list[:x - 1])
    s += sub * kai(N - i - 1)  
    num_list[x - 1] = 0
  return s

#print(number(P), number(Q))
print(abs(number(P) - number(Q)))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from itertools import permutations

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

l = []
for s in permutations(range(1,n+1)):
    l.append("".join(map(str,s)))

l = sorted(l)

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

print(abs(a-b))

Submission status: Accepted

Solution code:
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("A:", A)

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

Submission status: Accepted

Solution code:
import math

N = int(input())
P = input().split()
Q = input().split()
X = [i+1 for i in range(N)]
Y = [i+1 for i in range(N)]

n = 1
m = 1
for i in range(N):
    for j in range(N-i):
        if int(P[i]) == X[j]:
            l = j
        if int(Q[i]) == Y[j]:
            k = j
    X.remove(int(P[i]))
    Y.remove(int(Q[i]))
    n += l*math.factorial(N-i-1)
    m += k*math.factorial(N-i-1)
    
print(abs(m-n))

Submission status: Accepted

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

seq =(i for i in range(1,n+1))
l = list(itertools.permutations(seq))
print(abs(l.index(p)-l.index(q)))

Submission status: Accepted

Solution code:
import math

N = int(input())
P = input().split()
Q = input().split()
X = [i+1 for i in range(N)]
Y = [i+1 for i in range(N)]

n = 1
for i in range(N):
    for j in range(N-i):
        if int(P[i]) == X[j]:
                l = j
    X.remove(int(P[i]))
    n += l*math.factorial(N-i-1)
m = 1
for i in range(N):
    for j in range(N-i):
        if int(Q[i]) == Y[j]:
                l = j
    Y.remove(int(Q[i]))
    m += l*math.factorial(N-i-1)
print(abs(m-n))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P,Q = input().rstrip().split(" "),input().rstrip().split(" ")

for i in range(N):
  P[i],Q[i] = int(P[i]),int(Q[i])

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

for i in range(len(a)):
  if a[i] == tuple(P):
    pindex= i+1
  if a[i] == tuple(Q):
    qindex= i+1
    
print(abs(pindex-qindex))

Submission status: Accepted

Solution code:
import itertools
import numpy as np

N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
N_list = list(range(1, N+1, 1))
N_dictionary = list(itertools.permutations(N_list))
N_dic = [list(n) for n in N_dictionary]
a = N_dic.index(P)
b = N_dic.index(Q)
ans = np.abs(a - b)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline


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

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
P = tuple(int(i) for i in input().split())
Q = tuple(int(i) for i in input().split())

seq = tuple(range(1,N+1))
import itertools
p_list = list(itertools.permutations(seq))
for i,p in enumerate(p_list):
  if p == P:
    p_idx = i
  if p == Q:
    q_idx = i
print(abs(p_idx-q_idx))