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 = input().split()
P = "".join(P)

Q = input().split()
Q = "".join(Q)

dictionary = list(itertools.permutations([str(j+1) for j in range(N)], N))
dictionary = list(map("".join, dictionary))
print(abs(dictionary.index(P)-dictionary.index(Q)))

Submission status: Accepted

Solution code:
import itertools as it
n=int(input())
q=list(map(int,input().split()))
b=list(map(int,input().split()))
List = list(it.permutations(list( range(1,n+1) )))
a=c=0
for i in range(len(List)):
    if(List[i]==tuple(q)):
        a=i
    if(List[i]==tuple(b)):
        c=i
print(abs(a-c))

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
la=[0]*n
lb=[0]*n
ans=0

for i in range(n):
  la[i]=i+1
  lb[i]=i+1


def kaijo(n):
  if n>0:
    return n*kaijo(n-1)
  else:
    return 1

for i in range(n):
  sa=la.index(a[i])
  sb=lb.index(b[i])
  ans+=kaijo(n-i-1)*(sa-sb)
  la.pop(sa)
  lb.pop(sb)

print(abs(ans))

Submission status: Accepted

Solution code:
import sys
import math
import itertools

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

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

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

Submission status: Accepted

Solution code:
import itertools

def list_to_str(arr): 
    s = map(str, arr)
    s = ','.join(s).replace(',', '')
    return s

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


junretsu = []
for v in itertools.permutations(P, n):
    junretsu.append(list_to_str(list(v)))

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

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

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

Submission status: Accepted

Solution code:
import itertools

n = int(input())

p = input().replace(' ', '')
q = input().replace(' ', '')

array = []
for v in itertools.permutations(list(map(str,range(1, n+1)))):
  tmp = list(v)
  array.append(''.join(tmp))
  
array.sort()

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

Submission status: Accepted

Solution code:
import itertools

def AllPatern(n, all):
    numbers = []
    all = []
    for i in range(n):
        numbers.append(i+1)
    for i in itertools.permutations(numbers):
        all.append(list(i))

    return all


def WhichNumber(p, q, all):
    val_p = 0
    val_q = 0
    for i in range(len(all)):
        val_p += 1
        if p == all[i]:
            break
    for i in range(len(all)):
        val_q += 1
        if q == all[i]:
            break

    return val_p, val_q

def main():
    n = int(input())
    p = [int(i) for i in input().split()]
    q = [int(i) for i in input().split()]
    all = []

    all = AllPatern(n, all)
    val_p, val_q = WhichNumber(p, q, all)
    print(abs(val_p - val_q))



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools
N=int(input())
P,Q=[list(map(int,input().split())) for i in range(2)]
dictionary=sorted(itertools.permutations(P,N))
print(abs(dictionary.index(tuple(P))-dictionary.index(tuple(Q))))

Submission status: Accepted

Solution code:
'''
https://atcoder.jp/contests/abc150/tasks/abc150_c
'''
def main():
    import sys
    #input = sys.stdin.readline
    sys.setrecursionlimit(10000000)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations
    #from itertools import accumulate, product
    from math import floor, ceil
    #from operator import itemgetter

    #mod = 1000000007


    n = int(input())
    a = tuple(map(int, input().split()))
    b = tuple(map(int, input().split()))
    for i, x in enumerate(permutations(range(1, n+1), n)):
        if a==x:
            a = i
        if b==x:
            b = i
    print(abs(a-b))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools

n = int(input())
nums = [i for i in range(1, n+1)]
p = tuple(map(int, input().split(" ")))
q = tuple(map(int, input().split(" ")))

count = 0
p_v = None
q_v = None
for i, v in enumerate(itertools.permutations(nums, n)):
    if v == p:
        count += 1
        p_v = i
    if v == q:
        count += 1
        q_v = i
    if count == 2:
        break

print(abs(q_v-p_v))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
permutations_lis = itertools.permutations(range(1,n+1))# 全ての場合のリストを生成
dis_list = []
for i,case in enumerate(permutations_lis):
    if list(case) == p :
        a = i 
    if list(case) == q :
        b = i
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
n=int(input())
l=list(itertools.permutations(range(1,n+1),n))

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

for i in range(len(l)):
    if l[i]==a:
        a_index=i+1
    elif l[i]==b:
        b_index=i+1
    else:
        continue
if a_index==0 or b_index==0:
    print(0)
else:    
    result=abs(a_index-b_index)
    print(result)

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

i = 0
p, q = 0, 0
for v in itertools.permutations(range(1,N+1)):
    if P == list(v):
        p = i
    if Q == list(v):
        q = i
    i += 1

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

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


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

Submission status: Accepted

Solution code:
import itertools
N=int(input())
ptuple=tuple(map(int,input().split()))
qtuple=tuple(map(int,input().split()))
permlist=list(itertools.permutations(range(1,N+1)))

pindex=0
qindex=0
for i,perm in enumerate(permlist):
  if ptuple==perm:
    pindex=i
  if qtuple==perm:
    qindex=i
    
print(abs(pindex-qindex))

Submission status: Accepted

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

a = [i for i in range(1, n+1)]
b = list(itertools.permutations(a, n))
c = []
for i in range(len(b)):
    c.append(list(b[i]))


ans_p = 0
ans_q = 0
for i in range(len(c)):
    if c[i] == p:
        ans_p = i+1
    if c[i] == q:
        ans_q = i+1

print(abs(ans_p-ans_q))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
# coding: utf-8
from fractions import gcd 
from functools import reduce
import sys
sys.setrecursionlimit(200000000)
from inspect import currentframe


# my functions here!
#標準エラー出力
def printargs2err(*args):
    names = {id(v):k for k,v in currentframe().f_back.f_locals.items()}
    print(', '.join(names.get(id(arg),'???')+' : '+repr(arg) for arg in args),file=sys.stderr)
def debug(x):
    print(x,file=sys.stderr)
def printglobals():
    for (symbol, value) in globals().items():
        print('symbol="%s"、value=%s' % (symbol, value),file=sys.stderr)
def printlocals():
    for (symbol, value) in locals().items():
        print('symbol="%s"、value=%s' % (symbol, value),file=sys.stderr)
#入力（後でいじる）
def pin(type=int):
    return map(type,input().split())


"""
"""

#solution:


        
#input
def resolve():
    N,=pin()
    P=tuple(pin())
    Q=tuple(pin())
    
    from itertools import permutations as pm
    a=list(range(1,N+1))
    for k,item in enumerate(pm(a)):
        
        if item==P:
            p=k
            
        if item==Q:
            q=k
    print(abs(p-q))    
    #print([["NA","YYMM"],["MMYY","AMBIGUOUS"]][cMMYY][cYYMM])
#if __name__=="__main__":resolve()
"""
#printデバッグ消した？
#前の問題の結果見てないのに次の問題に行くの？
"""
"""
お前カッコ閉じるの忘れてるだろ
"""
import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """3
1 3 2
3 1 2"""
        output = """3"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1"""
        output = """17517"""
        self.assertIO(input, output)
    def test_入力例_3(self):
        input = """3
1 2 3
1 2 3"""
        output = """0"""
        self.assertIO(input, output)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
import itertools

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

lst = list(itertools.permutations(P))

a = 0
b = 0
for i in lst:
    if i <= P:
        a += 1
    if i <= Q:
        b += 1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p, q = [tuple(map(int, input().split())) for _ in range(2)]

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

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

Submission status: Accepted

Solution code:
# nの定義
n = int(input())

# p,qの定義
p, q = [list(map(int, input().split())) for _ in range(2)]

# 全体数,nListを定義
sumN = 1
pList = [0] * n
qList = [0] * n
for i in range(n):
    sumN *= i + 1
    pList[i] = i + 1
    qList[i] = i + 1

sumN = sumN // n

pSum = 0
qSum = 0

for i in range(n - 1):
    pSum += pList.index(p[i]) * sumN
    pList.pop(pList.index(p[i]))

    qSum += qList.index(q[i]) * sumN
    qList.pop(qList.index(q[i]))

    sumN = sumN // (n - i - 1)

print(abs(pSum - qSum))

Submission status: Accepted

Solution code:
import itertools

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

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

seq = list(itertools.permutations(seq))

for j in range(len(seq)):
    if list(seq[j]) == p:
        a = j + 1

    if list(seq[j]) == q:
        b = j + 1

if a > b:
    res = a - b
else:
    if a < b:
        res = b - a

print(res)

Submission status: Accepted

Solution code:
f=lambda:tuple(map(int,input().split()))
n=int(input())
tp,tq=f(),f()
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:
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))

from itertools import permutations

order = list(range(1, n+1))
a = 0
b = 0
cnt = 0
flag = False
for i in permutations(order, n):
    if list(i) == p:
        a = cnt
    if list(i) == q:
        b = cnt
    cnt += 1

print(abs(a-b))

Submission status: Accepted

Solution code:
def main():
    from itertools import permutations
    import sys
    input=sys.stdin.readline
    n=int(input())
    p=tuple(map(int,input().split()))
    q=tuple(map(int,input().split()))
    
    cnt=1
    for i in permutations(range(1,n+1)):
        if i==p:
            pi=cnt
        if i==q:
            qi=cnt
        cnt+=1
    
    print(abs(pi-qi))
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np
def fact(M):
    if M == 1:
        return 1
    else:
        return fact(M-1)*M
def count(N, X):
    number = np.arange(N)+1
    res = 1
    for i in range(N-1):
        idx = int(np.where(number == X[i])[0])
        res = res + fact(N-i-1) * idx
        number = np.delete(number,idx)
    return res

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

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

Submission status: Accepted

Solution code:
import itertools

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

x = sorted(P)
xl = list(itertools.permutations(x))

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

a = xl.index(tp)
b = xl.index(tq)

ans = abs(a - b)

print(ans)

Submission status: Accepted

Solution code:
import itertools

n = int(input())
a = ''.join(input().split())
b = ''.join(input().split())

List = [''.join(map(str, i)) for i in itertools.permutations(range(1, n+1), n)]
List.sort()

a_ind = List.index(a)
b_ind = List.index(b)

print(abs(a_ind-b_ind))

Submission status: Accepted

Solution code:
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
fact=[1,1,2,6,24,120,720,5040]
ans=0
for i in range(n-1):
    p0,q0=sorted(p[i:]),sorted(q[i:])
    ans+=(p0.index(p[i])-q0.index(q[i]))*fact[n-i-1]
print(abs(ans))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
Pi = 0
Qi = 0
l = [i+1 for i in range(N)]
for i, retu in enumerate(itertools.permutations(l), 1):
    if P == retu:
        Pi = i
    if Q == retu:
        Qi = i

print(abs(Pi-Qi))

Submission status: Accepted

Solution code:
import  itertools as it

n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
cnt=[]
for i in range(1,n+1):
    cnt.append(i)
tmp=[]
for conbinations in it.permutations(cnt):
    tmp.append(list(conbinations))

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

Submission status: Accepted

Solution code:
import itertools

n = int(input())

p = list(input().split())
q = list(input().split())

x = sorted(p)

xx = list(itertools.permutations(x))

tp = tuple(p)
tq = tuple(q)

a = xx.index(tp)
b = xx.index(tq)

ans = abs(a - b)

print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations

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

dic_perm = list(permutations(range(1,n+1)))
print(abs(dic_perm.index(p)-dic_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()))

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

Submission status: Accepted

Solution code:
import itertools

n = int(input())

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

if p == q:
    print(0)
else:
    count = 1
    for per in itertools.permutations(range(1,n+1)):
        if per == p:
            a = count
        elif per == q:
            b = count
        count += 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()))

iP = -1
iQ = -1
for idx, perm in enumerate(permutations(range(1, N+1))):
    lp = list(perm)
    if lp == P:
        iP = idx
    if lp == Q:
        iQ = idx
print(abs(iP - iQ))

Submission status: Accepted

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

*perm, = itertools.permutations(list(range(1, n+1)), n)
a = bisect.bisect_right(perm, p)
b = bisect.bisect_right(perm, q)

print(abs(a-b))

Submission status: Accepted

Solution code:
import math
import itertools
lis=[]
N=int(input())
P=list(map(int, input().split()))
Q=list(map(int, input().split()))
l=[i+1 for i in range(N)]
"""
lP=[i+1 for i in range(N)]
lQ=[i+1 for i in range(N)]
#print(P,Q,lP,lQ)
bangoP=[]
bangoQ=[]
pnum=0
qnum=0
for i in range(N):
    j=0
    while True:
        if (lP[j]==P[i]):
            bangoP.append(j)
            #print(j)
            lP.pop(j)
            #print(lP)
            break
        j=j+1
for i in range(N):
    j=0
    while True:
        if (lQ[j]==Q[i]):
            bangoQ.append(j)
            #print(j)
            lQ.pop(j)
            #print(lQ)
            break
        j=j+1
#print(bangoP,bangoQ)

for i in range(N-1):
    #print(bangoP[i],bangoQ[i])
    pnum=pnum+math.factorial(N-1-i)*bangoP[i]
    qnum=qnum+math.factorial(N-1-i)*bangoQ[i]
print(abs(pnum-qnum))
"""
p_list=list(itertools.permutations(l))
for i in range(len(p_list)):
    if P==list(p_list[i]):
        pnum=i
    if Q==list(p_list[i]):
        qnum=i
print(abs(pnum-qnum))

Submission status: Accepted

Solution code:
import math
lis=[]
N=int(input())
P=list(map(int, input().split()))
Q=list(map(int, input().split()))
lP=[i+1 for i in range(N)]
lQ=[i+1 for i in range(N)]
#print(P,Q,lP,lQ)
bangoP=[]
bangoQ=[]
pnum=0
qnum=0
for i in range(N):
    j=0
    while True:
        if (lP[j]==P[i]):
            bangoP.append(j)
            #print(j)
            lP.pop(j)
            #print(lP)
            break
        j=j+1
for i in range(N):
    j=0
    while True:
        if (lQ[j]==Q[i]):
            bangoQ.append(j)
            #print(j)
            lQ.pop(j)
            #print(lQ)
            break
        j=j+1
#print(bangoP,bangoQ)

for i in range(N-1):
    #print(bangoP[i],bangoQ[i])
    pnum=pnum+math.factorial(N-1-i)*bangoP[i]
    qnum=qnum+math.factorial(N-1-i)*bangoQ[i]
print(abs(pnum-qnum))

'''
wacount=0
account=0
count=0
zero=0
flag=1
cur=0
changeflag=1
#s=[list(input()) for i in range(2)] 
#for range(M):
#print(N,M)
 
for i in range(M):
     lis=input().split()
     #print(lis)
     lis[0]=int(lis[0])
     lis.append(i)
     #print(lis)
     s.append(lis)
 
s2=sorted(s,key=lambda x:x[0])
sorted(s2,key=lambda x:x[2])
j=1
for i in range(len(s2)):
    if s2[i][0]>j:
        j=s2[i][0]
        flag=1
        count=0
    if (s2[i][0]==j)and(flag==1):
        if s2[i][1]=="WA":
            count=count+1
        elif s2[i][1]=="AC":
            account=account+1
            wacount=wacount+count
            flag=0
            count=0
                
print(account,wacount)
s=[]
lis=[]
N,M=map(int, input().split())
wacount=0
account=0
count=0
zero=0
flag=1
cur=0
changeflag=1
#s=[list(input()) for i in range(2)] 
#for range(M):
#print(N,M)
 
for i in range(M):
     lis=input().split()
     #print(lis)
     lis[0]=int(lis[0])
     lis.append(i)
     #print(lis)
     s.append(lis)
 
s2=sorted(s,key=lambda x:x[0])
sorted(s2,key=lambda x:x[2])
j=1
for i in range(len(s2)):
    if s2[i][0]>j:
        j=s2[i][0]
        flag=1
        count=0
    if (s2[i][0]==j)and(flag==1):
        if s2[i][1]=="WA":
            count=count+1
        elif s2[i][1]=="AC":
            account=account+1
            wacount=wacount+count
            flag=0
            count=0
print(account,wacount)
'''

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n=ii()

p=limss()
q=limss()

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

pans=0
qans=0
if p==q:
    print(0)
    exit()

for i,j in enumerate(range(factorial(n))):

    if "".join(p)=="".join(list(map(str,arr[i]))):
        pans=j
    elif "".join(q)=="".join(list(map(str,arr[i]))):
        qans=j
    
print(abs(pans-qans))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import itertools
import sys


def solve(N: int, P: "List[int]", Q: "List[int]"):
    perm = list(itertools.permutations(range(1, N+1)))
    pi = perm.index(tuple(P))
    qi = perm.index(tuple(Q))
    ans = abs(pi - qi)
    print(ans)


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    Q = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, P, Q)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import permutations

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

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

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = input().split()
q = input().split()
p = "".join(p)
q = "".join(q)
l = []
for i,x in enumerate(itertools.permutations(range(1,n+1))):
    l.append("".join(map(str,list(x))))
d = {}
l.sort()
for i,x in enumerate(l):
    d.update({x:i+1})
print(abs(d[p]-d[q]))

Submission status: Accepted

Solution code:
from itertools import permutations, combinations

n = int(input())
p_array = [int(x) for x in input().split()]
q_array = [int(x) for x in input().split()]
comb = sorted(permutations(p_array, n))
d = {comb[x]: x + 1 for x in range(len(comb))}
print(abs(d[tuple(p_array)]- d[tuple(q_array)]))

Submission status: Accepted

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

L = list(permutations(range(1,N+1)))
L.sort()

for i in L:
  if i == P:
    a = L.index(i)
  if i == Q:
    b = L.index(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()))

L = list(itertools.permutations(range(1,N+1)))
L.sort()
for l in L:
    if l == P:
        a = L.index(l)
    if l == Q:
        b = L.index(l)
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

def solve():
  n = int(input())
  p = list(int(i) for i in input().split())
  q = list(int(i) for i in input().split())
  
  query = [int(i) for i in range(1,n+1)]
  tp = itertools.permutations(query,n)
  i = 0
  for tb in tp:
    i += 1
    if list(tb) == p:
      a = i
    if list(tb) == q:
      b = i
  print(abs(b-a))
          
solve()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

from itertools import permutations

def main():
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))
    pm = sorted(permutations(range(1, n + 1)))
    for i, x in enumerate(pm):
        if x == p:
            ip = i
        if x == q:
            iq = i
    print(abs(ip - iq))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p_list = list(map(int, input().split()))
q_list = list(map(int, input().split()))
p_list_perm_sorted = sorted(list(itertools.permutations(p_list)))
q_list_perm_sorted = sorted(itertools.permutations(q_list))
print(abs(p_list_perm_sorted.index(tuple(p_list)) - q_list_perm_sorted.index(tuple(q_list))))

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(1,n+1):
  l.append(i)
def chk(a,b):
  for i in range(len(a)):
    if a[i]!=b[i]:
      return False
  return True
p_list=list(permutations(l))
#a=0
#b=0
for i in range(len(p_list)):
  if chk(p_list[i],p):
    a=i
  if chk(p_list[i],q):
    b=i
print(abs(a-b))

Submission status: Accepted

Solution code:
import math
from functools import reduce
from collections import deque
import itertools
import sys
sys.setrecursionlimit(10**7)

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

n = int(input())
p = input()
q = input()

p_count = 1
q_count = 1

def kaijo(n):
    ret = 1
    for i in range(n):
        ret *= n
    return ret

for rrr in itertools.permutations(map(str,range(1,n+1))):
    s = " ".join(rrr)
    if s < p:
        p_count += 1
    if s < q:
        q_count += 1


print(abs(p_count - q_count))

Submission status: Accepted

Solution code:
from itertools import permutations

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

perms = list(permutations(range(1, n + 1)))
a = perms.index(p)
b = perms.index(q)

print(abs(a - b))

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
input_nums = lambda: list(map(int, input().split()))

import itertools

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

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

index_P = all.index(P)
index_Q = all.index(Q)
print(abs(index_P - index_Q))

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

def fact(n):
    num = 1
    for i in range(1, n+1):
        num *= i
    return num


def order(N, P):
    order = 0
    L = [i for i in range(1, N + 1)]
    """
    下からN桁目が一定なグループは(N-1)!個
    下から(N-1)桁目が一定なグループは(N-2)!個
    ...
    下からi桁目(1 <= i <= N)が一定なグループは(i-1)!個
    ...
    下から1桁目が一定なグループは0!個
    """
    for i in range(N):
        order += bisect_left(L, P[i]) * fact(N - i - 1)
        L.remove(P[i])
        #print("bisect={}, fact={}, order={}, L={}".format(bisect_left(L, P[i]), fact(N - i - 1), order, L))
    return order + 1

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

Submission status: Accepted

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

from itertools import permutations

lst = list(permutations(range(1,n+1)))
lst.sort()
print(abs(lst.index(P) - lst.index(Q)))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read 
input = sys.stdin.buffer.readline
def inputS(): return input().rstrip().decode()
readlines = sys.stdin.buffer.readlines 

from itertools import permutations

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

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import bisect
import re
import queue
from collections import Counter
from collections import defaultdict
from functools import lru_cache


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def float():
        return float(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def map_float():
        return [float(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def PI():
        return math.acos(-1)

    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def roundUp(a, b):
        return -(-a // b)

    @staticmethod
    def toUpperMultiple(a, x):
        return Math.roundUp(a, x) * x

    @staticmethod
    def toLowerMultiple(a, x):
        return (a // x) * x

    @staticmethod
    def nearPow2(n):
        if n <= 0:
            return 0
        if n & (n - 1) == 0:
            return n
        ret = 1
        while(n > 0):
            ret <<= 1
            n >>= 1
        return ret

    @staticmethod
    def sign(n):
        if n == 0:
            return 0
        if n < 0:
            return -1
        return 1

    @staticmethod
    def isPrime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True

    @staticmethod
    def divisor(n):
        i = 1
        table = []
        while i * i <= n:
            if n % i == 0:
                table.append(i)
                table.append(n // i)
            i += 1
        table = list(set(table))
        return table


class PriorityQueue:
    def __init__(self, l=[]):
        self.__q = l
        heapq.heapify(self.__q)
        return

    def push(self, n):
        heapq.heappush(self.__q, n)
        return

    def pop(self):
        return heapq.heappop(self.__q)

    def list(self):
        return self.__q

    def length(self):
        return len(self.__q)


sys.setrecursionlimit(1000000)
MOD = int(1e09) + 7
INF = int(1e30)


def main():
    # sys.stdin = open("Sample.txt")
    N = Scanner.int()
    P = tuple(Scanner.map_int())
    Q = tuple(Scanner.map_int())
    perm = list(itertools.permutations([i + 1 for i in range(N)]))
    print(abs(perm.index(P) - perm.index(Q)))
    return


if __name__ == "__main__":
    main()