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 sys
import math
import itertools
stdin = sys.stdin
mod = 10**9 + 7

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
sa = lambda h: [list(map(int, stdin.readline().split())) for i in range(h)]

n = ni()
p = tuple(na())
q = tuple(na())

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

Submission status: Accepted

Solution code:
import itertools as it

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

l=[n for n in range(1,N+1)]
p=list(it.permutations(l))
a=p.index(P);b=p.index(Q)
ans=abs(b-a)

print(ans)

Submission status: Accepted

Solution code:
import itertools as it

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

l=[n for n in range(1,N+1)]
for i,t in enumerate(it.permutations(l)):
    if t==P:
        a=i+1
    if t==Q:
        b=i+1
ans=abs(b-a)

print(ans)

Submission status: Accepted

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

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


def f(val):
    for i, x in enumerate(N):
        if x == val:
            return i+1

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

Submission status: Accepted

Solution code:
def main():
    from itertools import permutations
    N = int(input())
    P = tuple([i for i in input().split()])
    Q = tuple([i for i in input().split()])

    if P == Q:
        print(0)
        return

    if ''.join(P) > ''.join(Q):
        T = P[::]
        P = Q
        Q = T

    per = ''.join([str(i) for i in range(1, N + 1)])
    cnt = 0
    p_found = False
    for S in permutations(per):
        if not p_found:
            if S == P:
                p_found = True
        else:
            cnt += 1
            if S == Q:
                break

    print(cnt)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import permutations

n=int(input())
li = list(range(1,n+1))
lis = list(permutations(li))

def solve(x):
	for i in range(len(lis)):
		if list(lis[i]) == x:
			return i

p = list(map(int,input().split()))
q = list(map(int,input().split()))
print(abs(solve(p) - solve(q)))

Submission status: Accepted

Solution code:
import itertools

N = int(input())

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

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

mp = {}

for x in itertools.permutations(A):
    mp[x] = len(mp)

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

Submission status: Accepted

Solution code:
import itertools

n = int(input())
pl = list(map(int, input().split()))
ql = list(map(int, input().split()))

count = 0
a, b = 0, 0

for v in itertools.permutations(range(1, n+1)):
    count += 1
    if pl == list(v):
        a = count
    if ql == list(v):
        b = count

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

a = 0
b = 0
i = 1

for x in itertools.permutations(list(range(1,N+1))):
    l = list(x)
    if P == l:
        a = i
    if Q == l:
        b = i
    i += 1

print(abs(a - b))

Submission status: Accepted

Solution code:
import itertools as it
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
d = []
ans = []
for i in range(1,n+1):
    d.append(i)
for i in it.permutations(d,n):
    ans.append(list(i))
print(abs(ans.index(p)-ans.index(q)))

Submission status: Accepted

Solution code:
N=int(input())
p=(int(x) for x in input().split())
q=(int(x) for x in input().split())
import itertools
seq = [(i +1) for i in range(N)]
h=list(itertools.permutations(seq))
print(abs(h.index(tuple(p)) - h.index(tuple(q))))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
nums = []
for i in range(1, N + 1):
    nums.append(i)
Per = list(itertools.permutations(nums, N))
a = Per.index(P)
b = Per.index(Q)
print(abs(a - b))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import array
from bisect import *
from collections import *
import fractions
import heapq
from itertools import *
import math
import random
import re
import string
import sys

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

shff = list(range(1, N + 1))
idx1 = -1
idx2 = -1
for i, perm in enumerate(permutations(shff)):
    if perm == P:
        idx1 = i
    if perm == Q:
        idx2 = i
print(abs(idx1 - idx2))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
cnt = 0
cnt1 = 0
cnt2 = 0
a = []
for i in range(1, n+1):
    a.append(i)

for j in itertools.permutations(a):
    cnt += 1
    jk = list(j)
    if jk == p:
        cnt1 = cnt
    if jk == q:
        cnt2 = cnt
print(abs(cnt1 - cnt2))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = "".join([i for i in input().split(" ")])
q = "".join([i for i in input().split(" ")])
yes = "".join([str(i) for i in range(1, n+1)])
perms = sorted(list(set(["".join(i) for i in list(itertools.permutations(yes))])))
a = perms.index(p)
b = perms.index(q)
print(abs(a-b))

Submission status: Accepted

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

N = int(readline())

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

cnt = 0
for k in permutations(list(range(1, N+1))):
    cnt += 1
    if P == k:
        p = cnt
    if Q == k:
        q = cnt
print(abs(p-q))

Submission status: Accepted

Solution code:
from itertools import permutations

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

arr = [p for p in permutations(range(1, n + 1), n)]
print(abs(arr.index(p) - arr.index(q)))

Submission status: Accepted

Solution code:
from math import factorial


def cntRank(S, n):
    used = set()
    cnt = 0

    for i, s in enumerate(S):
        s = int(s)
        j = 1
        while j < s:
            if j not in used:
                cnt += factorial(n - (i + 1))
            j += 1
        used.add(s)

    return cnt + 1


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

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

Submission status: Accepted

Solution code:
import itertools

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

a = 0
b = 0

for i, j in enumerate(itertools.permutations(r)):
    if list(j) == p:
        a = i
    if list(j) == q:
        b = i

print(abs(b-a))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
Ps = ''
Qs = ''
for i in P:
    Ps += str(i)
for i in Q:
    Qs += str(i)
seq = (str(i) for i in range(1,N+1))
per = itertools.permutations(seq)
a = 0
b = 0
for i,s in enumerate(per):
    str1 = ''
    for c in s:
        str1 += c
    if str1 == Ps:
        a = i + 1
    if str1 == Qs:
        b = i + 1

print(abs(a-b))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from itertools import permutations
n = int(input())
f = list(map(int, input().split()))
e = list(map(int, input().split()))
a = sorted(f)
first = 0
end = 0
for i, l in enumerate(permutations(a)):
    if list(l) == f:
        first = i
    if list(l) == e:
        end = i

print(abs(end-first))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
lis = list(map(int,input().split()))
li = list(map(int,input().split()))
su = ""
for i in range(n):
    su += str(1+i)
cnt = 1
for x in itertools.permutations([i for i in range(1,n+1)]):
    if list(x) == lis:
        a1 = cnt
    if list(x) == li:
        a2 = cnt
    cnt += 1
print(abs(a2-a1))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7 # 998244353
input=lambda:sys.stdin.readline().rstrip()
class BIT(object):
    def __init__(self,A,dot,e,inv=None):
        n=len(A)
        self.__n=n
        self.__dot=dot
        self.__e=e
        self.__inv=inv
        self.__node=['$']+A # 1-indexed
        for i in range(1,n+1):
            j=i+(i&-i)
            if(j<=n): self.__node[j]=dot(self.__node[i],self.__node[j])

    def add(self,i,w=1):
        i+=1
        while(i<=self.__n):
            self.__node[i]=self.__dot(self.__node[i],w)
            i+=i&-i

    def sum(self,i):
        i+=1
        res=self.__e
        while(i>0):
            res=self.__dot(res,self.__node[i])
            i-=i&-i
        return res

from operator import add
def resolve():
    n=int(input())
    A=list(map(lambda x:int(x)-1,input().split()))
    A.reverse()

    bit=BIT([0]*n,add,0)
    fact=1
    ans=0
    for i in range(n):
        a=A[i]
        s=bit.sum(a)
        ans+=fact*s
        bit.add(a)
        fact*=i+1
    p=ans

    A=list(map(lambda x:int(x)-1,input().split()))
    A.reverse()


    bit=BIT([0]*n,add,0)
    fact=1

    ans=0
    for i in range(n):
        a=A[i]
        s=bit.sum(a)
        ans+=fact*s
        bit.add(a)
        fact*=i+1
    q=ans

    print(abs(p-q))
resolve()

Submission status: Accepted

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

def calc(L):
    n = len(L)
    if n == 1: return 0
    a =  len([l for l in L if l < L[0]])
    return a * fact[n-1] + calc(L[1:])

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

print(abs(calc(P) - calc(Q)))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
from itertools import permutations

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N = INT()
P = tuple(LIST())
Q = tuple(LIST())

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

Submission status: Accepted

Solution code:
import sys
from itertools import permutations

n = int(sys.stdin.readline().rstrip())
p, q = [tuple(map(int, sys.stdin.readline().split())) for _ in range(2)]

def main():
    perms = list(permutations(range(1, n+1)))
    return abs(perms.index(p) - perms.index(q))

if __name__ == '__main__':
    ans = main()
    print(ans)

Submission status: Accepted

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

from itertools import permutations

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

M = tuple(permutations(Z,N))

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

print(abs(a-b))

Submission status: Accepted

Solution code:
import math
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
def ans(r):
  c = 0
  nn = list(range(1,n+1))
  for i in range(n):
    c += (nn.index(r[i])-1) * math.factorial(n-i-1)
    nn.remove(r[i])
  return c
print(abs(ans(p)-ans(q)))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = [int(a)-1 for a in input().split()]
Q = [int(a)-1 for a in input().split()]
i = 0
ans = 0
for a in itertools.permutations(range(N), N):
    a = [b for b in a]
    if a == P:
        ans -= i
    if a == Q:
        ans += i
    i += 1

print(abs(ans))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = "".join(list(map(str, input().split())))
q = "".join(list(map(str, input().split())))

l = "".join([str(i+1) for i in range(n)])

cnt = 0
a,b = 0,0
for x in itertools.permutations(l):
	y = "".join(x)
	cnt += 1
	if y == p:
		a = cnt
	if y == q:
		b = cnt

	if a != 0 and b != 0:
		break

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

def GenerateArray(number):
    data = []
    for i in range(number):
        data.append(i+1)
    return data

def CheckArrayOrder(data, Array, count=0):
    for i in itertools.permutations(data):
        count += 1
        if list(i) == Array:
            return count
    return False

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

data = GenerateArray(number)

print(abs(CheckArrayOrder(data, P) - CheckArrayOrder(data, Q)))

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
a=tuple(map(int, input().split()))
b=tuple(map(int, input().split()))
x=[i for i in range(1,n+1)]
x=list(permutations(x))
x.sort()
print(abs(x.index(a)-x.index(b)))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P_list = tuple(map(int, input().split()))
Q_list = tuple(map(int, input().split()))
raw = list(itertools.permutations(range(1, N+1)))
print(abs(raw.index(P_list) - raw.index(Q_list)))

Submission status: Accepted

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

def calc_(x,n):
    ans = 0
    for i in range(n-1):
        ans += x[i] - 1
        ans *= (n-1-i)
        for j in range(i+1 , n):
            if(x[j] > x[i]):
                x[j] -= 1
    return ans

print( abs(calc_(p,n) - calc_(q,n)))

Submission status: Accepted

Solution code:
import itertools

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

l = list(i for i in range(1, n+1))
j = list(list(i) for i in itertools.permutations(l, n))

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

Submission status: Accepted

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

def dic(z):
    # sorted(list(itertools.permutations(z))) の中に辞書順に並べられた順列が入っている
    return sorted(list(itertools.permutations(z))).index(tuple(z)) + 1
 
print(abs(dic(p) - dic(q)))

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

import itertools

seq = range(1,N+1)
for i,l in enumerate(itertools.permutations(seq)):
    if l == P:
        ans1 = i
    if l == Q:
        ans2 = i
print(abs(ans1-ans2))

Submission status: Accepted

Solution code:
import itertools
# math.factorial()

N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
V = [i for i in range(1,N+1)]

cnt_p = 0
cnt_q = 0
cnt = 0

for v in itertools.permutations(V, N):
    cnt += 1
    if P == v:
        cnt_p = cnt
    if Q == v:
        cnt_q = cnt

print(abs(cnt_p - cnt_q))

Submission status: Accepted

Solution code:
import itertools 


n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
kind = [i for i in range(1, n+1)]
li = list(itertools.permutations(kind))
a = li.index(p)
b = li.index(q)

print(abs(a-b))

Submission status: Accepted

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

N=int(input())
list_P=list(map( int, input().split() ))
list_Q=list(map( int, input().split() ))

#-----
list_all=list(itertools.permutations(range(1,N+1)))


def check_order(list_X,list_all):
  check=""
  less_num=0
  
  for L_all in list_all:
    for i in range(N):
      if list_X[i] > L_all[i] :
        check="true"
        break
      elif list_X[i] < L_all[i]:
        break
    
    if check=="true":
      less_num += 1
      check=""
  return less_num + 1
  

a=check_order(list_P, list_all)
b=check_order(list_Q, list_all)

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import math

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

perm = sorted(list(itertools.permutations([str(int(i+1)) for i in range(n)])))
for i in range(math.factorial(n)):
    if list(perm[i]) == p:
        a = i + 1
    if list(perm[i]) == q:
        b = i + 1
print(abs(a-b))

Submission status: Accepted

Solution code:
import math

N = int(input())
P_list = list(map(int, input().split()))
Q_list = list(map(int, input().split()))
N_list = list(range(1, N + 1))

current_permutation = [0] * N
current_index = 0
A = 0
B = 0
def dfs(i, current_permutation):

    # 終了条件
    if i >= N:
        global current_index
        current_index += 1
        global A
        global B
        if current_permutation == P_list:
            A = current_index
        if current_permutation == Q_list:
            B = current_index

        if A != 0 and B != 0:
            print(abs(A - B))
            exit()

        return

    for j in range(N):
        if (N_list[j] in current_permutation) == False:
            current_permutation[i] = N_list[j]
            dfs(i + 1, current_permutation)
            current_permutation[i] = 0

dfs(0, current_permutation)

Submission status: Accepted

Solution code:
from itertools import permutations

n = int(input())
per = []
for i in permutations(range(1, n+1)):
    per.append(i)

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

a = per.index(p)
b = per.index(q)

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()))
for n, v in enumerate(itertools.permutations(range(1,N+1),  N)):
  if v == P:
    a = n
  if v == Q:
    b = n
print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations

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

ls = list(permutations(range(1,N+1)))
tup_p = tuple(P)
tup_q = tuple(Q)

print(abs(ls.index(tup_p)-ls.index(tup_q)))

Submission status: Accepted

Solution code:
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)))
ps = permutations.index(p)
qs = permutations.index(q)

print(abs(ps-qs))

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
a=tuple(map(int, input().split())) 
b=tuple(map(int, input().split())) 
l=list(i for i in permutations(range(1,n+1)))
print(abs((l.index(a))-(l.index(b))))

Submission status: Accepted

Solution code:
n=int(input())
p=[int(j) for j in input().split()]
q=[int(j) for j in input().split()]
l=list(range(1,n+1)[::-1])
import itertools
ll=[]
for x in itertools.permutations(l):
    ll.append(list(x))
ll.sort()
a=0
b=0
c=0
for i in ll:
    if i==p:
        a=c
    if i==q:
        b=c
    c+=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()))

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

Submission status: Accepted

Solution code:
import itertools

n = int(input())

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

falist = [0, 1]
for i in range(2, n):
    falist.append(falist[i-1] * i)
falist = falist[::-1]

pscore = 0
qscore = 0
for i in range(n-1):
    for j in range(i, n):
        if p[i] > p[j]:
            pscore += falist[i]
for i in range(n-1):
    for j in range(i, n):
        if q[i] > q[j]:
            qscore += falist[i]

print(abs(pscore - qscore))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = input().split()
q = input().split()
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = a[:n]
p2 = str(p).strip("[]\'")
p3 = p2.replace("\'", "")
q2 = str(q).strip("[]\'")
q3 = q2.replace("\'", "")

cnt = 0
cnta, cntb = 0, 0
for i in itertools.permutations(b, n):
    cnt += 1
    if str(i).strip('()') == p3:
        cnta = cnt
    if str(i).strip('()') == q3:
        cntb = cnt
print(abs(cnta - cntb))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def sort_number(N,S):
    a=1
    for k in range(0,N,1):
        j=min(S)
        r=S.pop(0)
        if j!=r:
            l=0
            for i in S:
                if i < r:l+=1
            a+=l*math.factorial(N-k-1)
    return a
# 整数の入力
import math
N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
a=sort_number(N,P)
b=sort_number(N,Q)
c=int(math.fabs(a-b))
print(c)

Submission status: Accepted

Solution code:
import itertools

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

l = [i+1 for i in range(n)]
m =[]

for v in itertools.permutations(l, n):
    m.append(list(v))

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

print(abs(a - b))

Submission status: Accepted

Solution code:
import itertools

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

a = 0
b = 0
idx = 1
for i in list(itertools.permutations(range(1, n+1))):
  if p == list(i):
    a = idx
  if q == list(i):
    b = idx
    
  if a > 0 and b > 0:
    break
  idx+=1
  
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()))

PP = tuple(P)

A = list(itertools.permutations(range(1,N+1)))
PW = (A.index(P))
QW = (A.index(Q))

print(abs(PW-QW))

Submission status: Accepted

Solution code:
#coding:utf-8
import sys
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something : print(*something) if DEBUG else 0
DEBUG = False
def main(given = sys.stdin.readline):
    input = lambda : given().rstrip()
    LMIIS = lambda : list(map(int,input().split()))
    II = lambda : int(input())
    XLMIIS = lambda x : [LMIIS() for _ in range(x)]

    N = II()
    P = LMIIS()
    Q = LMIIS()
    from math import factorial

    def index(P):
        candidates = list(range(1,N+1))
        ans = 0
        f = factorial(N-1)
        for i in range(N-1):
            ans += candidates.index(P[i]) * f
            candidates.remove(P[i])
            f //= N-i-1
        return ans + 1

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

    



   




if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np

def surprise(x):
    #x!を計算
    res = 1
    for i in range(1, x +1):
        res = res * i
    return res

def zyun(x, N):
    num = 0
    for i in range(N):
        x = np.where(x >x[0], x -1, x)
        num += (x[0] -1) * surprise(x.size -1) #最初の数字*{(xの長さ-1)!}
        x = x[1:] #最初の数字を削除
    return num   

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

x_1 = np.empty(0, dtype = np.int32)
x_2 = np.empty(0, dtype = np.int32)

for i in P:
    x_1 = np.append(x_1, i)
for i in Q:
    x_2 = np.append(x_2, i)

print(np.abs(zyun(x_1, N) -zyun(x_2, N)))

Submission status: Accepted

Solution code:
import math

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

k1 = 0
for i in range(1,l):
  n = 1
  for m in a[:i]:
    if m < a[i-1]:
      n = n+1
  k1 = k1 + (a[i-1]-n)*(math.factorial(l-i))

k2 = 0
for i in range(1,l):
  n = 1
  for m in b[:i]:
    if m < b[i-1]:
      n = n+1
  k2 = k2 + (b[i-1]-n)*(math.factorial(l-i))

    
print(abs(k1 - k2))

Submission status: Accepted

Solution code:
import itertools

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

D=list(range(1,N+1))
dict=[]

for i,j in enumerate(itertools.permutations(D)):
    j=list(j)
    if j==P:
        p=i
    if j==Q:
        q=i
print(abs(p-q))

Submission status: Accepted

Solution code:
#coding:utf-8
import sys
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something : print(*something) if DEBUG else 0
DEBUG = False
def main(given = sys.stdin.readline):
    input = lambda : given().rstrip()
    LMIIS = lambda : list(map(int,input().split()))
    II = lambda : int(input())
    XLMIIS = lambda x : [LMIIS() for _ in range(x)]

    N = II()
    P = LMIIS()
    Q = LMIIS()
    from math import factorial

    def index(P):
        candidates = list(range(1,N+1))
        ans = 0
        for i in range(N-1):
            ans += candidates.index(P[i]) * factorial(N-1-i)
            candidates.remove(P[i])
        return ans + 1

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

    



   




if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import permutations


class Solution:
    def CountOrder(self, sequence1, sequence2):
        l = list(permutations(range(1, n + 1)))
        index1 = l.index(sequence1)
        index2 = l.index(sequence2)
        return abs(index1 - index2)


if __name__ == "__main__":
    n = int(input())
    sequence1 = tuple(map(int, input().split()))
    sequence2 = tuple(map(int, input().split()))
    solution = Solution()
    print(solution.CountOrder(sequence1, sequence2))

Submission status: Accepted

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

def countdic(n):
    cn=1
    p = 1
    for j in range(N-1):
        cn = sum(n[j]>x for x in n[j+1:len(n)])
        p +=cn*math.factorial(len(n)-1-j)
    return p
print(abs(countdic(P)-countdic(Q)))

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc150/submissions/9394047

from itertools import permutations

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

perms = tuple(permutations(range(1, N + 1)))
p = perms.index(P)
q = perms.index(Q)
print(abs(p - q))

Submission status: Accepted

Solution code:
import itertools
import math
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
l=[]
for i in itertools.permutations(range(1,n+1)):
    l.append(list(i))
for i in range(math.factorial(n)):
    if l[i]==p:
        a=i+1
    if l[i]==q:
        b=i+1
ans=abs(a-b)
print(ans)

Submission status: Accepted

Solution code:
import itertools
n = list(range(1, int(input())+1))
p, q = input(), input()
a = [str(x) for x in n]
new_list = []
for x in itertools.permutations(a):
    new_list.append(" ".join(x))
print(abs(new_list.index(p) - new_list.index(q)))

Submission status: Accepted

Solution code:
from itertools import*
n,a,b=eval('eval(input().replace(" ",",")),'*3)
i=list(permutations(range(1,n+1))).index
print(abs(i(a)-i(b)))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
n = int(input())
per = []
p = list(map(str,input().split()))
q = list(map(str,input().split()))
def dfs(num):
    if len(num) == n:
        per.append(int(num))
        
    for i in range(1,n+1):
        if str(i) not in num:
            dfs(num+str(i))
            
        
dfs("")
p = "".join(p)
q = "".join(q)
p = int(p)
q = int(q)
a = per.index(p)
b = per.index(q)
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
ansa=0
ansb=0

q=list(itertools.permutations(range(1,n+1)))
for i in range(len(q)):
  if a==list(q[i]):
    ansa=i+1
  if b==list(q[i]):
    ansb=i+1
print(abs(ansa-ansb))

Submission status: Accepted

Solution code:
import numpy as np
import itertools

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

seq = [str(i+1) for i in range(N)]
  
permutation = list(itertools.permutations(seq))


P_index = permutation.index(P)
Q_index = permutation.index(Q)

answer = abs(Q_index-P_index)
print(int(answer))

Submission status: Accepted

Solution code:
import itertools

N=int(input())
P=int("".join(input().split()))
Q=int("".join(input().split()))
A=[]
for i in range(N):
    A.append(str(i+1))
B=list(itertools.permutations(A))

k=0
while int("".join(B[k]))!=P:
    k+=1
j=0
while int("".join(B[j]))!=Q:
    j+=1
print(abs(k-j))

Submission status: Accepted

Solution code:
from itertools import permutations

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

def rank(a):
  return sum([tu<a for tu in list(permutations(range(1,n+1),n))])

print(abs(rank(p)-rank(q)))

Submission status: Accepted

Solution code:
import numpy as np
import itertools

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

num_list = [i+1 for i in range(N)]
a = list(itertools.permutations(num_list)).index(P)
b = list(itertools.permutations(num_list)).index(Q)
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()))
 
l = list(itertools.permutations(range(1, n+1)))
a = l.index(p)
b = l.index(q)
 
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()))
nlis=[i for i in range(1,N+1)]
 
j=list(itertools.permutations(nlis))
cp=j.index(P)+1
cq=j.index(Q)+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()))
nlis=[i for i in range(1,N+1)]

j=list(itertools.permutations(nlis))
cp=j.index(P)+1
cq=j.index(Q)+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()))
PP=tuple(P)
A=list(itertools.permutations(range(1,N+1)))
PW=(A.index(P))
QW=(A.index(Q))
print(abs(PW-QW))

Submission status: Accepted

Solution code:
import itertools


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