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:
def solve():
    from itertools import permutations
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))

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

    d = {i: j for j, i in enumerate(t)}
    print(abs(d[p] - d[q]))

solve()

Submission status: Accepted

Solution code:
import itertools

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


c = list(itertools.permutations(X,N))

a=0
b=0
for i in range(len(c)):
    if c[i]==P:
        a=i+1
    if c[i]==Q:
        b=i+1

print(abs(a-b))

Submission status: Accepted

Solution code:
N=int(input())
X=list(map(int,input().split()))
Y=list(map(int,input().split()))
a=1
b=1
def josu(x):
  if x==1 or x==0:
    return 1
  else:
    return x*josu(x-1)
A=list(range(1,N+1))
B=list(range(1,N+1))
for i in range(N-1):
  if X[i]!=min(A):
    z=A.index(X[i])
    a+=z*josu(N-(i+1))
  A.remove(X[i])
for j in range(N-1):
  if Y[j]!=min(B):
    z=B.index(Y[j])
    b+=z*josu(N-(j+1))
  B.remove(Y[j])
if a-b>=0:
  print(a-b)
else:
  print(b-a)

Submission status: Accepted

Solution code:
import math
import itertools
n = int(input())
s = tuple(map(int,input().split()))
t = tuple(map(int,input().split()))

ari = [i for i in range(1,n+1)]
l = list(itertools.permutations(ari))
for i in range(math.factorial(n)):
    if s == l[i]:
        a = i
    if t == l[i]:
        b = i
if a >= b:
    print(a-b)
else:
    print(b-a)

Submission status: Accepted

Solution code:
from itertools import permutations

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

cnt_p = 1
for case in permutations(range(1, n+1)):
    if p == list(case):
        p_n = cnt_p
    cnt_p += 1

cnt_q = 1
for case in permutations(range(1, n+1)):
    if q == list(case):
        q_n = cnt_q
    cnt_q += 1
print(abs(p_n - q_n))

Submission status: Accepted

Solution code:
from itertools import permutations as perm
from collections import deque, Counter as cnt
from collections import defaultdict as dd
from operator import itemgetter as ig
from bisect import bisect_right as bsr
from math import factorial, ceil, floor
import sys
sys.setrecursionlimit(1000000)

# お約束
args = None
INF = float("inf")
MOD = int(1e9 + 7)


def input(*ps):
    if type(ps[0]) is list:
        return [input(*ps[0][:-1]) for _ in range(ps[0][-1])]
    elif len(ps) == 1:
        return ps[0](next(args))
    else:
        return [p(next(args)) for p in ps]


def nlist(n, v):
    if not n:
        return [] if type(v) is list else v
    return [nlist(n[1:], v) for _ in range(n[0])]


def yesno(v, yes="Yes", no="No", upper=False):
    if upper:
        print([yes.upper(), no.upper()][not v])
    else:
        print([yes, no][not v])


def main():
    """エントリーポイント"""
    N = input(int)
    P = input([int, N])
    Q = input([int, N])
    p, q = tuple(P), tuple(Q)

    base = [x for x in range(1, N + 1)]
    base_list = sorted(perm(base))
    pn, qn = -1, -1
    for c, x in enumerate(base_list):
        if x == p:
            pn = c
        if x == q:
            qn = c
    print(abs(pn - qn))


if __name__ == '__main__':
    args = iter(sys.stdin.read().split())
    main()

Submission status: Accepted

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

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

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 = [i+1 for i in range(n)]
for i,per in enumerate(list(permutations(a))):
    if per == p:
        x = i
    if per == q:
        y = i
print(abs(x-y))

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.buffer.readline
#from collections import defaultdict
#d = defaultdict(int)
#import fractions
#import math
#import collections
#from collections import deque
#from bisect import bisect_left
#N = int(input())
#A = list(map(int,input().split()))
#S = list(input())
#S.remove("\n")
#N,M = map(int,input().split())
#S,T = map(str,input().split())
#A = [int(input()) for _ in range(N)]
#S = [input() for _ in range(N)]
#A = [list(map(int,input().split())) for _ in range(N)]
#import itertools
import itertools
n = int(input())
t = [i+1 for i in range(n)]
li = list(itertools.permutations(t))
p = list(map(int,input().split()))
q = list(map(int,input().split()))
p = tuple(p)
q = tuple(q)
pp = li.index(p)
qq = li.index(q)
print(abs(pp-qq))

Submission status: Accepted

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

l = []
for i in range(1,n+1):
    l.append(str(i))

cnt = 1
for v in itertools.permutations(l, n):
    if p == list(v):
        a = cnt

    if q == list(v):
        b = cnt
    cnt = cnt + 1

print(abs(a-b))

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import math
N = int(input())
X = list(map(int,input().split()))
Y = list(map(int,input().split()))
X_ans = 0
Y_ans = 0
used_numX = list()
used_numY =list()
for i in range(N-1):
    if(i == N-2):
        if(X[i]>X[i+1]):
            X_ans +=2
        else:
            X_ans +=1
        if(Y[i]>Y[i+1]):
            Y_ans +=2
        else:
            Y_ans +=1


    else:
        used_x = used_y =0
        for j in range(len(used_numX)):
            if(used_numX[j]<=X[i]):
                used_x +=1
            if(used_numY[j]<=Y[i]):
                used_y +=1
    
        X_ans += math.factorial(N-1-i)*(X[i]-1-used_x)
        Y_ans += math.factorial(N-1-i)*(Y[i]-1-used_y)
        used_numX.append(X[i])
        used_numY.append(Y[i])

print(abs(X_ans-Y_ans))

Submission status: Accepted

Solution code:
def factorial(n):
    res = 1
    for i in range(n):
        res*=(i+1)
    return res

def order(n, li):
    res=0
    for i in range(n):
        j=sorted(li[n-i-1:n]).index(li[n-i-1])
        res+=factorial(i)*j
    return res

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

p_ord=order(n,p)
q_ord=order(n,q)

print(abs(p_ord-q_ord))

Submission status: Accepted

Solution code:
import sys
import itertools

readline = sys.stdin.readline

def main():
    N = int(input())
    P = tuple(map(int, readline().split()))
    Q = tuple(map(int, readline().split()))
    
    dictN = list(itertools.permutations(range(1, N+1)))
    p = dictN.index(P)
    q = dictN.index(Q)
    ans = abs(p-q)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import itertools

n = int(input())
perm_a = [int(x) for x in input().split()]
perm_b = [int(x) for x in input().split()]
perm_a = tuple(perm_a)
perm_b = tuple(perm_b)


ind_a = -1
ind_b = -1
for i, perm in enumerate(itertools.permutations(range(1, n+1))):
    if perm == perm_a:
        ind_a = i
    if perm == perm_b:
        ind_b = i

print(abs(ind_b - ind_a))

Submission status: Accepted

Solution code:
import sys
import itertools
input = sys.stdin.readline
n=int(input())
p=list(input().split())
q=list(input().split())
a=0

for i in range(1,n+1):
    a=a*10+i
b=list(itertools.permutations(str(a),n))
d=b.index(tuple(q))
e=b.index(tuple(p))
c=abs(d-e)
print(c)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools

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

tmp=list()
for i in range(n):
    tmp.append(i+1)
perm=list(itertools.permutations(tmp))

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

Submission status: Accepted

Solution code:
import itertools

n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
r=[list(i) for i in itertools.permutations(range(1,n+1))]
print(abs(r.index(p)-r.index(q)))

Submission status: Accepted

Solution code:
def kaijo(x):
    if(x <= 2):
        return x
    else:
        return x*kaijo(x-1)

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

count_p = 0
count_q = 0
for i in range(n):
    count_p = count_p + (p[i]-1) * kaijo(n-i-1)
    for j in range(i+1,n):
        if(p[i] < p[j]):
            p[j] = p[j] - 1
    count_q = count_q + (q[i]-1) * kaijo(n-i-1)
    for j in range(i+1,n):
        if(q[i] < q[j]):
            q[j] = q[j] - 1

print(abs(count_p - count_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()))

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

Submission status: Accepted

Solution code:
from math import floor,ceil,sqrt,factorial,log
from collections import Counter, deque
from functools import reduce
import numpy as np
import itertools
def S(): return input()
def I(): return int(input())
def MS(): return map(str,input().split())
def MI(): return map(int,input().split())
def FLI(): return [int(i) for i in input().split()]
def LS(): return list(MS())
def LI(): return list(MI())
def LLS(): return [list(map(str, l.split() )) for l in input()]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def LLSN(n: int): return [LS() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]

n = I()

P = LI()
Q = LI()

tp = tuple(P)
tq = tuple(Q)

combination = sorted(list(itertools.permutations(P, n)))
a = 0
b = 0
for i, v in enumerate(combination):
    if v == tp:
      if a == 0:
        a = i+1

    if v == tq:
      if b == 0:
        b = i+1
    
print(np.absolute(a-b))

Submission status: Accepted

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

from itertools import permutations

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

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

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P_list = list(map(int, input().split()))
Q_list = list(map(int, input().split()))
sort_list = sorted(P_list)
factorial_list = list(itertools.permutations(sort_list))
a = 1 + factorial_list.index(tuple(P_list))
b = 1 + factorial_list.index(tuple(Q_list))
print(abs(a-b))

Submission status: Accepted

Solution code:
import math
def difference(li):
  x=[int(i) for i in range(1,n+1)]
  l=len(li)
  sum=0
  for i in range(l):
    sum+=math.factorial(l-i-1)*(x.index(li[i]))
    x.remove(li[i])  
  return sum+1

n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
r1=difference(p)
r2=difference(q)
result=abs(r1-r2)
print(result)

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
import math
nP = 1
nQ = 1
n = N-1
work = [i for i in range(1, N+1)]
for p in P:
    nP += work.index(p) * math.factorial(n)
    work.remove(p)
    n -= 1
n = N-1
work = [i for i in range(1, N+1)]
for q in Q:
    nQ += work.index(q) * math.factorial(n)
    work.remove(q)
    n -= 1
print(abs(nP-nQ))

Submission status: Accepted

Solution code:
import sys

n = int(sys.stdin.readline().rstrip())
*p, = map(int, sys.stdin.readline().split())
*q, = map(int, sys.stdin.readline().split())

factorial = [1] * (n + 1)
for i in range(n): factorial[i+1] = factorial[i] * (i + 1)

def main():
    d = 0
    a = [0] * (n + 1); b = [0] * (n + 1)
    for i in range(n - 1):
        a[p[i]] = b[q[i]] = 1
        c1 = c2 = 0
        for j in range(1, p[i]): c1 += a[j]
        for j in range(1, q[i]): c2 += b[j]
        d += ((q[i] - c2) - (p[i] - c1)) * factorial[n-(i+1)]
    print(abs(d))

if __name__ ==  '__main__':
    main()

Submission status: Accepted

Solution code:
import math
from collections import deque
import copy

n = int(input())
pL = list(input().split(" "))
qL = list(input().split(" "))

q = deque()
li = list(map(str, range(1, n + 1)))

for i in range(1, n + 1):
    q.append(str(i))

while True:
    item = q.popleft()
    if len(item) == n:
        q.appendleft(item)
        break
    for s in li:
        if not s in list(item):
            q.append(item + s)

idx = 1
pi, qi = 0, 0
while len(q) != 0:
    item = q.popleft()
    if item == "".join(pL):
        pi = idx
    if item == "".join(qL):
        qi = idx
    idx += 1

print(abs(qi - pi))

Submission status: Accepted

Solution code:
n = int(input())
aa = list(map(int, input().split()))
bb = list(map(int, input().split()))

def getcnt(aa):
    cnt = 0
    for i in range(len(aa)):
        cnt *= len(aa) - i
        cnt += aa[i] - 1
        for j in range(i+1,len(aa)):
            if aa[j] > aa[i]:
                aa[j] -= 1
    return cnt+1

print(abs(getcnt(aa) -getcnt(bb)) )

Submission status: Accepted

Solution code:
from itertools import permutations
import math

N = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
perm = list(permutations(range(1, N + 1)))
a = None
b = None

for i in range(math.factorial(N)):
    if perm[i] == tuple(p):
        a = i + 1
    if perm[i] == tuple(q):
        b = i + 1

print(abs(a - b))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
#n,p=map(int,input().split())
pl=list(map(int,input().split()))
ql=list(map(int,input().split()))
#l=[list(map(int,input().split())) for i in range(n)]

import itertools
l=[i for i in range(1,n+1)]

p = list(itertools.permutations(l))
p.sort()
a=p.index(tuple(pl))
b=p.index(tuple(ql))

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
pn = tuple(map(int, input().split()))
qn = tuple(map(int, input().split()))

n_list = list(range(1, n+1))
counter = 1

for i in itertools.permutations(n_list, n):
  if pn == i:
    a = counter
  if qn == i:
    b = counter
  counter += 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()))

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

Submission status: Accepted

Solution code:
N = int(input())
P = ''.join([str(v) for v in input().split()])
Q = ''.join([str(v) for v in input().split()])

items = [str(v) for v in range(1,N+1)]
used = [False for _ in range(N+1)]
junretu = list()

def dfs(now):
    if len(now) == N:
        junretu.append(now)
        return
    for i,v in enumerate(items):
        if used[int(v)]:
            continue
        
        used[int(v)] = True
        dfs(now+v)
        used[int(v)] = False
    return

dfs('')
sorted_junretu = sorted(list(junretu))

p_d,q_d = 0,0

for i,s in enumerate(sorted_junretu):
    if s == P:
        p_d = i
    if s == Q:
        q_d = i

print(abs(p_d-q_d))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
# tuple:listの中に()で要素を表すi.e.[(1,2)(2,3)]

l = list(itertools.permutations(P)) #イテレータ
m = sorted(l)
a = m.index(P)
b = m.index(Q)
ans = abs(a - b) #abs:正の数を返す
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()))

xs = [i+1 for i in range(N)]
perms = permutations(xs,N)
cntp = cntq = 0
for i,(perm) in enumerate(perms):
    
    if list(perm) == ps: cntp = i
    if list(perm) == qs: cntq = i
print(abs(cntp-cntq))

Submission status: Accepted

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

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

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

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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from itertools import permutations

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

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

a = p.index(tuple(P))
b = p.index(tuple(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()))

pmt = list(itertools.permutations(range(1, N+1)))
pmtP = pmt.index(P)
pmtQ = pmt.index(Q)
print(abs(pmtP - pmtQ))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = [int(x) for x in input().split()]
P = tuple(P)
Q = [int(x) for x in input().split()]
Q = tuple(Q)
N_ = list(range(1, N+1))

R = list(itertools.permutations(N_))

Pflg = Qflg = False
Pcnt = Qcnt = -1
for i, r in enumerate(R):
    if P==r:
        Pflg = True
        Pcnt = i
    if Q==r:
        Qflg = True
        Qcnt = i
    if Pflg and Qflg:
        break

print(abs(Pcnt - Qcnt))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p_inputs = tuple([int(i) for i in input().split()])
q_inputs = tuple([int(i) for i in input().split()])

#順列の組み合わせを出力する
li = list(itertools.permutations(range(1,n+1),n))

print(abs(li.index(p_inputs)-li.index(q_inputs)))

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
l=[]
for i in range(n):
    l.append(i+1)
dic= sorted(list(permutations(l,n)))
r=len(dic)
dicp=0
dicq=0
for x in range(r):
    dic[x]=list(dic[x])
    if dic[x]==p:
        dicp=x+1
    if dic[x]==q:
        dicq=x+1
print(max(dicp-dicq,dicq-dicp))

Submission status: Accepted

Solution code:
from itertools import permutations
from bisect import bisect_left

n = int(input())
p = int(input().replace(" ", ""))
q = int(input().replace(" ", ""))

temp_list = [int("".join(temp)) for temp in permutations([str(x) for x in range(1, n + 1)])]
temp_list.sort()

ans = abs(bisect_left(temp_list, p) - bisect_left(temp_list, q))
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list
#from itertools import combinations # (string,3) 3回
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    import itertools
    n = int(input())
    # indexの中身 を 使うときは, list じゃなくて、 tuple じゃないとだめええ
    p = tuple(map(int,input().split()))
    q = tuple(map(int,input().split()))
    # 初期リスト
    num = [i + 1 for i in range(n)]
    per = list(itertools.permutations(num))
    # permutations 全て tuple だから 合わせろ!
    print(abs(per.index(q) - per.index(p)))



if __name__ == '__main__':
  main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from itertools import permutations

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

for i, order in enumerate(permutations(range(1,N+1))):
    if list(order) == P:
        a = i
    if list(order) == 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()))
P=tuple(P)
Q=tuple(Q)
l=[]
R=[]
for i in range(N):
    l.append(i+1)
for i in itertools.permutations(l,N):
    R.append(i)
x=R.index(P)
y=R.index(Q)
print(abs(x-y))

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(str, input().split(' ')))
Q = list(map(str, input().split(' ')))
ans = []
now = []

def CulucPermutation(array, now, level):
    if level==N:
        ans.append(''.join(now))
        #print('return and level=',level)
        return
    for i in range(0,N):
        if array[i] not in now:
            now += [array[i]]
            #print('bp',now, level, i)
            CulucPermutation(array, now, level+1)
            now.pop()
            #print('ap',now, level, i)
        else:
            pass

def main():
    # 順列の元となる値をlist格納
    n = []
    for i in range(1,N+1):
        n += [str(i)]
    # 順列を全列挙して結果をリストans(文字型)にため込む
    CulucPermutation(n, now, 0)
    # PとQを文字列化して場所を特定、計算する。
    p = ''.join(P)
    q = ''.join(Q)
    print(abs(ans.index(p) - ans.index(q)))

if __name__=='__main__':
    main()

Submission status: Accepted

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

a,b=0,0
A=sorted([i for i in permutations(P)])
for j,i in enumerate(A):
    i=list(i)
    if i==P:a=j+1
    if i==Q:b=j+1
print(abs(a-b))

Submission status: Accepted

Solution code:
# ABC150C - Count Order

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

a,b=0,0

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

for i in range(n-1):
    for j in range(n):
        if l[j]==p[i]:
            l.pop(j)
            break
    tmp=j
    for j in range(1,n-i):
        tmp*=j
    a+=tmp

#print(a)

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

for i in range(n-1):
    for j in range(n):
        if l[j]==q[i]:
            l.pop(j)
            break
    tmp=j
    for j in range(1,n-i):
        tmp*=j
    b+=tmp

#print(b)
        
print(abs(a-b))

Submission status: Accepted

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


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

    p_cnt = 0
    q_cnt = 0
    i = 0
    for temp in itertools.permutations([i + 1 for i in range(n)]):
        i += 1
        if temp == p:
            p_cnt = i
        if temp == q:
            q_cnt = i

        if p_cnt != 0 and q_cnt != 0:
            break

    return abs(q_cnt - p_cnt)


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

Submission status: Accepted

Solution code:
from itertools import permutations

N = int(input())
P = "".join(input().split())
Q = "".join(input().split())
L = []
perm = permutations(range(1, N + 1), N)
for p in perm:
    s = "".join(map(str, list(p)))
    L.append(s)
L.sort()
print(abs(L.index(P) - L.index(Q)))

Submission status: Accepted

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

    n_list = list(range(1, N+1))
    n_perm = permutations(n_list, N)
    p_i, q_i = 0, 0
    for i, p in enumerate(n_perm):
        if P == list(p):
            p_i = i
        if Q == list(p):
            q_i = i
    print(abs(p_i - q_i))


if __name__ == '__main__':
    q3()

Submission status: Accepted

Solution code:
import math

N = int(input())
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]
sort_P = []
sort_Q = []
count_A = 1
count_B = 1
count_sum = 1

for i in range(len(P) - 1):
    x = P.pop(0)
    y = Q.pop(0)
    sort_P.append(x)
    sort_Q.append(y)
    sort_P.sort()
    sort_Q.sort()
    count_A += (x - sort_P.index(x) - 1) * math.factorial(N - 1 - i)
    count_B += (y - sort_Q.index(y) - 1) * math.factorial(N - 1 - i)

print(abs(count_A - count_B))

Submission status: Accepted

Solution code:
'''
INPUT SHORTCUTS
N, K = map(int,input().split())
N ,A,B = map(int,input().split())
string = str(input())
arr = list(map(int,input().split()))
N = int(input())
'''
from itertools import permutations 
N = int(input())
a = list(map(str,input().split()))
a = ''.join(a)
b = list(map(str,input().split()))
b = ''.join(b)
cnt=1
lena = 0
lenb = 0
inp = [ str(i) for i in range(1,N+1)]
inp = ''.join(inp)
perm = permutations(inp)
for i in list(perm):
	temp = ''.join(list(i))
	# print(temp)
	if temp==a:
		lena=cnt
	if temp==b:
		lenb=cnt
	cnt+=1
print(abs(lena-lenb))

Submission status: Accepted

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

P = it.permutations([i for i in range(1,n+1)],n)

a = 0
b = 0
cnt = 1
if p==q:
  print(0)
  exit()
for i in P:
  if p==i:
    a = cnt
    cnt +=1
  elif q==i :
    b = cnt
    cnt +=1
  else:
    cnt +=1
ans = abs(a-b)
print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations as pmt
 
N = int(input())
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]
 
a,b = None,None
i = 0
for od in pmt([i+1 for i in range(N)]):
    order = list(od)
    if P == order:
        a = i
    if Q == order:
        b = i
    i += 1
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()))

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

li = []
for i in permutations(R, N):
    li.append(list(i))

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

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),n))
l.sort()
for k,t in enumerate(l):
  if t==p:
    px = k+1
  if t==q:
    qx = k+1
print(abs(px-qx))

Submission status: Accepted

Solution code:
from itertools import permutations as par
n=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
i=0
for q in par([i+1 for i in range(n)]):
    q=list(q)
    if q==A: A=i
    if q==B: B=i
    i+=1
print(abs(A-B))

Submission status: Accepted

Solution code:
import itertools

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

nli = [i for i in range(1, n+1)]
# print(nli)

anss = list(itertools.permutations(nli, n))
# print(anss)

ans = abs(anss.index(ps) - anss.index(qs))
print(ans)

Submission status: Accepted

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

import itertools

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

     num = [x + 1 for x in range(n)]
     p_list = list(map(list, (itertools.permutations(num))))
     # print(p_list)
     idx_p = p_list.index(p)
     idx_q = p_list.index(q)

     print(abs(idx_p - idx_q))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import itertools

n = int(input())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
l3 = sorted(l1)
l = list("")
for i in itertools.permutations(l3):
    l.append(list(i))
print(abs(l.index(l1) - l.index(l2)))

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 = [i for i in range(1, N+1)]
cnt = 0
op = -1
oq = -1
for j in permutations(A):
  cnt += 1
  if(j == p):
    op = cnt
  if(j == q):
    oq = cnt
    
print(abs(op-oq))

Submission status: Accepted

Solution code:
import math
import itertools

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

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

junretu = list(itertools.permutations(n_list))
sorted(junretu)
idx_p = 0
idx_q = 0
for i in range(math.factorial(n)):
    if list(junretu[i]) == p:
        idx_p = i
    if list(junretu[i]) == q:
        idx_q = i
    elif idx_p != 0 and idx_q != 0:
        break

print(abs(idx_q - idx_p))

Submission status: Accepted

Solution code:
import itertools


def main():
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    l = [i for i in range(1, n + 1)]
    mp = {}
    for v in itertools.permutations(l, n):
        mp[v] = len(mp)
    print(abs(mp[p] - mp[q]))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools

num = int(input())
c = [i + 1 for i in range(num)]

a = tuple([int(i) for i in input().split(" ")])
b = tuple([int(i) for i in input().split(" ")])

a_num = 0
b_num = 0

for num,i in enumerate(itertools.permutations(c)):
    if a == i:
        a_num = num
    if b == i:
        b_num = num

print(abs(a_num - b_num))

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    p = tuple(int(i) for i in input().split())
    q = tuple(int(i) for i in input().split())
    from itertools import permutations 
    a = [i for i in range(1, n+1)]
    o1 = -1
    o2 = -1
    cnt = 0
    for i in permutations(a):
      cnt += 1
      if i == p:
          o1 = cnt
      if i == q:
          o2 = cnt
      ans = abs(o1-o2)
    print(ans)
main()

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
i=0
for j in permutations(range(1,n+1)):
  i+=1
  if list(j)==p:
      p=i
  if list(j)==q:
      q=i
print(abs(p-q))

Submission status: Accepted

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

def da(a,n):
    x = [1,2,3,4,5,6,7,8]
    y = x[:n]
    count = 0
    for v in itertools.permutations(y):
        w = list(v)
        if w == a:
            return count
        
        count += 1
print(abs(da(q,n)-da(p,n)))