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

n = int(input())
p = [x for x in map(int, input().split())]
q = [x for x in map(int, input().split())]
lst = [x for x in range(1,n+1)]

perm = itertools.permutations(lst)
permLst = [list(x) for x in perm]

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

print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations, combinations
from bisect import bisect_left, bisect
n= int(input())
a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))
lst = [x for x in range(1, n + 1)]
per = list(permutations(lst, n))
a_index = bisect_left(per, a)
b_index = bisect_left(per, b)
print(abs(a_index - b_index))

Submission status: Accepted

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

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

import itertools

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

Submission status: Accepted

Solution code:
n = int(input())
#a,b = map(int,input().split())
L1 = tuple(map(int,input().split()))
L2 = tuple(map(int,input().split()))
L = [x+1 for x in range(n)]

li = []
import itertools
for x in itertools.permutations(L,n):
    #print(x)
    li.append(x)
#print(li)
print(abs(li.index(L1)-li.index(L2)))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = ''.join(input().split())
q = ''.join(input().split())
a = 0
b = 0
cnt = 0

for iter in itertools.permutations(list(map(str, range(1, n+1)))):
    cnt += 1
    if(''.join(iter) == p): a = cnt
    if(''.join(iter) == q): b = cnt
    
    if(a*b): break
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()))

nums = [i for i in range(1, N+1)]
all_list = list(permutations(nums))
a = all_list.index(P)
b = all_list.index(Q)
print(abs(a-b))

Submission status: Accepted

Solution code:
#  Copyright: this code was written at 2020. for AtCoder by Silviase
import itertools

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
cnt1,fin = 0,False
cntp, cntq = 0, 0
listn = [(i + 1) for i in range(n)]
for x in itertools.permutations(listn):
    fin = False
    cntp += 1
    for i in range(n):
        if x[i] != p[i]:
            fin = True
    if not fin:
        break

for x in itertools.permutations(listn):
    fin = False
    cntq += 1
    for j in range(n):
        if x[j] != q[j]:
            fin = True
    if not fin:
        break
print(str(abs(cntp - cntq)))

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc140/tasks
import itertools
 
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))

# 組み合わせ抽出
pattern = list(itertools.permutations(P))

# 順番
dct = sorted(pattern)

a = 0
b = 0

for i in range(len(pattern)):
    if list(dct[i]) == P:
        a = i
    if list(dct[i]) == Q:
        b = i

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import sys

input = sys.stdin.readline


class AtCoder:
    def main(self):
        N = int(input())
        P = tuple(map(int, input().split()))
        Q = tuple(map(int, input().split()))
        perm = list(itertools.permutations(range(1, N + 1)))

        a, b = 0, 0
        for i, p in enumerate(perm):
            if p == P:
                a = i
            if Q == p:
                b = i

        print(abs(a - b))


# Run main
if __name__ == '__main__':
    AtCoder().main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(4100000)

import math

import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)

from itertools import permutations


def resolve():
    N = [int(x) for x in sys.stdin.readline().split()][0]
    p_list = [int(x) for x in sys.stdin.readline().split()]
    q_list = [int(x) for x in sys.stdin.readline().split()]
    logger.debug('{}'.format([N, p_list, q_list]))

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

    a = perm.index(tuple(p_list))
    b = perm.index(tuple(q_list))

    print(abs(a - b))


if __name__ == "__main__":
    resolve()

# AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す
# python -m unittest template/template.py で実行できる
# pypy3 -m unittest template/template.py で実行できる

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)

Submission status: Accepted

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

import itertools

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

l = [i for i in range(1, N + 1)]
permutation = list(itertools.permutations(l, N))
for i in range(len(permutation)):
    if list(permutation[i]) == P:
        a = i + 1
    if list(permutation[i]) == Q:
        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()))

s = ''
t = ''

for i in range(n):
    s += str(p[i]-1)
    t += str(q[i]-1)

li = list(itertools.permutations(range(n)))
li2 = []

for i in range(len(li)):
    x = ''
    for j in range(n):
        x += str(li[i][j])
    li2.append(x)

for i in range(len(li2)):
    if li2[i] == s:
        counts = i
    if li2[i] == t:
        countt = i

print(abs(counts - countt))

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
p="".join(input().split())
q="".join(input().split())
N=""
for i in range(1,n+1):
  N += str(i)
perms = list(permutations(N,n))
for i in range(len(perms)):
  perms[i] = "".join(list(perms[i]))

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

Submission status: Accepted

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

Submission status: Accepted

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

s = list(range(1, N+1))
for i in range(N):
    p += s.index(P[i]) * math.factorial(N-i-1)
    s.remove(P[i])

s = list(range(1, N+1))
for i in range(N):
    q += s.index(Q[i]) * math.factorial(N-i-1)
    s.remove(Q[i])

print(abs(p-q))

Submission status: Accepted

Solution code:


import itertools

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

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

p = 0
q = 0
for i,a in enumerate(A):
    for j in range(N):
        if a[j] != P[j]:
            break
        if j == N-1:
            p = i 

    if p != 0:
        break

for i,a in enumerate(A):
    for j in range(N):
        if a[j] != Q[j]:
            break
        if j == N-1:
            q = i 

    if q != 0:
        break

print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
list = []
clst = [i for i in range(1, N + 1)]
for i in itertools.permutations(clst, N):
    list.append(i)

acnt = 0
bcnt = 0
for i in range(len(list)):
    aF = True
    for j in range(N):
        if list[i][j] != P[j]:
            aF = False
            break
    if aF:
        acnt = i + 1

for i in range(len(list)):
    bF = True
    for j in range(N):
        if list[i][j] != Q[j]:
            bF = False
            break
    if bF:
        bcnt = i + 1
print(abs(acnt - bcnt))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = list(map(str,input().split()))
Q = list(map(str,input().split()))
num = list(map(str,range(1,N+1)))
nums = [''.join(v) for v in itertools.permutations(num)]

snums = sorted(nums)
Pnum = ''.join(P)
Qnum = ''.join(Q)
ans = abs(snums.index(Pnum)-snums.index(Qnum))
print(ans)

Submission status: Accepted

Solution code:
import itertools
import math
N=int(input())
A=list(itertools.permutations(range(1,N+1)))
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
count_P=0
count_Q=0
p=math.factorial(N)
for i in range(p):
    if P==A[i]:
        count_P=i
    if Q==A[i]:
        count_Q=i
print(abs(count_P-count_Q))

Submission status: Accepted

Solution code:
import itertools

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

l = [x+1 for x in range(n)]
ans = []
count = 0
for v in itertools.permutations(l):
    count += 1
    ans = list(v)
    if ans == a:
        a1 = count
    if ans == b:
        b1 = count

print(abs(a1-b1))

Submission status: Accepted

Solution code:
from math import factorial
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time
from fractions import gcd
#import random


def I(): return int(input())


def MI(): return map(int, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YN = ['No', 'Yes']
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']


# show_flg = False
show_flg = True

p = None
XY = None
N = None


def main():
    N = I()
    P = LI()
    Q = LI()
    # start = 0
    # finish = 0
    data = sorted(list(itertools.permutations(P, N)))

    for index, arr in enumerate(data):
        tmpS = 0
        tmpE = 0
        for i in range(N):
            if P[i] == arr[i]:
                tmpS += 1
            if Q[i] == arr[i]:
                tmpE += 1

        if tmpS == N:
            start = index

        if tmpE == N:
            finish = index

    print(abs(finish - start))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math

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

num_list =[1,2,3,4,5,6,7,8][:n]

p_count = 0
for i in range(n):
    order = num_list.index(p_list[i])
    num_list.pop(order)
    num = (order)*math.factorial(n-i-1)
    p_count = p_count + num

num_list =[1,2,3,4,5,6,7,8][:n]

q_count = 0
for i in range(n):
    order = num_list.index(q_list[i])
    num_list.pop(order)
    num = (order)*math.factorial(n-i-1)
    q_count = q_count + num

print(abs(p_count-q_count))

Submission status: Accepted

Solution code:
from itertools import permutations


def main(n, p, q):
    t = []

    for i, d in enumerate(permutations([_i for _i in range(1, n + 1)])):
        if d == p:
            t.insert(0, i)
        if d == q:
            t.insert(1, i)
        if len(t) == 2:
            break

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


if __name__ == "__main__":
    n = int(input())
    p = tuple(map(int, input().split(" ")))
    q = tuple(map(int, input().split(" ")))

    main(n, p, q)

Submission status: Accepted

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

import itertools
a=0
b=0
seq=range(1,N+1,1)
L=list(itertools.permutations(seq))
for i,l in enumerate(L):
  if P==l:
    a=i
  if Q==l:
    b=i
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

n=int(input())
l=[i+1 for i in range(n)]
p=tuple(map(int,input().split()))
q=tuple(map(int,input().split()))
cnt=0
P=0;Q=0
for i in itertools.permutations(l):
  cnt+=1
  if p==i:P=cnt
  if q==i:Q=cnt
print(abs(P-Q))

Submission status: Accepted

Solution code:
import itertools

a = int(input())
ans1=0
ans2=0
b=[]
for i in range(1,a+1):
    b.append(str(i))

p=list(map(str,input().split()))
q=list(map(str,input().split()))
count=0
for v in itertools.permutations(b):
    if list(v)==p:
        ans1=count+1
    if list(v)==q:
        ans2=count+1
    count+=1
print(abs(ans1-ans2))

Submission status: Accepted

Solution code:
import itertools


def main():
    N = int(input())
    PN = tuple(map(int, input().split()))
    QN = tuple(map(int, input().split()))

    a = 0
    for i, PN2 in enumerate(itertools.permutations(sorted(PN))):
        if PN == PN2:
            a = i

    b = 0
    for i, QN2 in enumerate(itertools.permutations(sorted(QN))):
        if QN == QN2:
            b = i

    print(abs(a - b))


main()

Submission status: Accepted

Solution code:
from itertools import permutations

N=int(input())
P=tuple(input().split(' '))
Q=tuple(input().split(' '))
l = [str(i) for i in range(1,N+1)]
p = permutations(l,N)
a = 0
b = 0
for n,i in enumerate(p):
    if i == P:
        a = n+1
    if i == Q:
        b = n+1
print(abs(a-b))

Submission status: Accepted

Solution code:
from math import factorial
import itertools

N = int(input())

P = input()
Q = input()

pNum = -1
qNum = -1
for i, vals in enumerate(itertools.permutations(range(1, N+1), N)):
    stri = ' '.join(map(str, vals))

    if stri == P:
        pNum = i+1
    if stri == Q:
        qNum = i+1

    if pNum != -1 and qNum != -1:
        break

print(abs(pNum-qNum))

Submission status: Accepted

Solution code:
import itertools

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

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

r=[]
for v in itertools.permutations(l):
    r.append(v)
    
pp=r.index(p)
qq=r.index(q)
print(abs(pp-qq))

Submission status: Accepted

Solution code:
import itertools

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

cnt = 0
k, l = 0, 0
for i in itertools.permutations(list(range(1,n+1))):
    cnt += 1
    if i == p:
        k = cnt
    elif i == q:
        l = cnt

if p == q:
    print(0)
else:
    print(abs(k-l))

Submission status: Accepted

Solution code:
import itertools

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

a, b = -1, -1
for i, L in enumerate(itertools.permutations(sorted(P), n)):
    if P == list(L):
        a = i
    if Q == list(L):
        b = i
print(abs(a - b))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
a = b = cnt = 0
R = []

for i in range(1,N+1):
  R.append(i)

for permutation in itertools.permutations(R):
  cnt += 1
  if permutation == P:
    a = cnt
  if permutation == Q:
    b = cnt

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

Submission status: Accepted

Solution code:
import itertools

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

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

print(abs(num_list.index(ps) - num_list.index(qs)))

Submission status: Accepted

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

# P=tuple([7, 3, 5, 4, 2, 1, 6, 8])
# Q=tuple([3 ,8 ,2 ,5 ,4 ,6 ,7 ,1])
# P=tuple([1 ,3 ,2])
# Q=tuple([3 ,1 ,2])

import itertools
# N=3
s=[i for i in range(1,N+1)]
number_id=0
id_p=0
id_q=0
for v in itertools.permutations(s):
    number_id+=1
#     print(number_id)
#     print(v)
    if v==P:
        id_p=number_id
    if v==Q:
        id_q=number_id
        
print(abs(id_p-id_q))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read

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

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

from itertools import permutations
L = list(range(1,n+1))
for i,c in enumerate(permutations(L)):
    if c == p:
        a = i
    elif c == q:
        b = i

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

perm = list(permutations([i+1 for i in range(N)]))

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

Submission status: Accepted

Solution code:
from fractions import gcd
# from datetime import date, timedelta
from heapq import*
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
# import sys
# sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
# input = sys.stdin.readline


def lcm(a, b):
    return a * b / fractions.gcd(a, b)

def main():
    n = int(input())
    p = list(map(int, input().split()))
    q = list(map(int, input().split()))
    a, b = -1, -1
    c = 0
    v = [i for i in range(1  , n+1)]
    for l in itertools.permutations(v):
        c+=1
        aa,bb = True,True
        for j in range(n):
            if p[j] != l[j]:
                aa = False
            
            if q[j] != l[j]:
                bb = False

        if aa:
            a = c
        if bb:
            b = c
    print(abs(a - b))
        


    # n = int(input())
    # s = input()
    # ans = 0
    # for i in range(n - 3):
    #     if s[i:i + 3] == "ABC":
    #         ans += 1
    # print(ans)
    # n, m = map(int, input().split())
    # a = list(map(int, input().split()))

    # g = lcm(a[0], a[1])
    # for i in range(2, n):
    #     g = lcm(g, a[i])
    # if g // 2 > m:
    #     print(0)
    #     exit()
    # print(g)
    # print(math.ceil(m//g + 0.5))



    


if __name__ == '__main__':
    main()

Submission status: Accepted

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

import itertools

p = 0
q = 0

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

print(abs(p - q))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
seq = [x for x in range(1,N+1)]
L = list(itertools.permutations(seq))
for i in range(len(L)):
    X = list(L[i])
    if X == P:
        a = i + 1
    if X == Q:
        b = i + 1
ans = abs(a-b)
print(ans)

Submission status: Accepted

Solution code:
import math

N = int(input())
P = input().split()
Q = input().split()
for a in range(N):
    P[a] = int(P[a])
    Q[a] = int(Q[a])

temp = [a for a in range(1, N+1)]
ans1 = 0
ans2 = 0

for a in range(N):
    ans1 += temp.index(P[a]) * math.factorial(N-a-1)
    temp.pop(temp.index(P[a]))


temp = [a for a in range(1, N+1)]

for a in range(N):
    ans2 += temp.index(Q[a]) * math.factorial(N-a-1)
    temp.pop(temp.index(Q[a]))

ans = ans1 - ans2
if ans < 0:
    ans *= -1

print(ans)

Submission status: Accepted

Solution code:
import itertools

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

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

pf, qf = False, False
for i in range(len(V)):
    if V[i] == tuple(P):
        p = i
        pf = True
    if V[i] == tuple(Q):
        q = i
        qf = True
    if pf and qf:
        break

print(abs(p-q))

Submission status: Accepted

Solution code:
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
def find_power(n):
    # 0!からn!までのびっくりを出してくれる関数
    powlist=[0]*(n+1)
    powlist[0]=1
    powlist[1]=1
    for i in range(2,n+1):
        powlist[i]=powlist[i-1]*i%(10**9+7)
    return powlist
powl=find_power(10)
import math
a=1
b=1
for i in range(n):
    c=1
    d=1
    subp=p[i:]
    subq=q[i:]
    for j in subp:
        if j<subp[0]:
            c+=1
    for k in subq:
        if k<subq[0]:
            d+=1

    a=a+c*int(powl[n-1-i])
    b=b+d*int(powl[n-1-i])
print(abs(a-b))

Submission status: Accepted

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

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

# 最小公倍数
def gcd(a, b):
  if a < b:
      a, b = b, a
  while a % b != 0:
      a, b = b, a % b
  return b
 
# 最大公約数 
def lcm(a, b):
  y = a*b / gcd(a, b)
  return int(y)

N = INT()
P = LIST()
Q = LIST()
s = sorted(P)


# for i in range(N):
#   a = P[i] * factorial(N - (i + 1))
  # print(a)
jun = list(itertools.permutations(s))
for i, l in enumerate(jun):
  if tuple(P) == l:
    a = i
  if tuple(Q) == l:
    b = i
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

def main():
    n = int(input())
    P = list(map(int, input().split()))
    Q = list(map(int, input().split()))

    l = range(1,n+1)
    for i, v in enumerate(itertools.permutations(l, n)):
        if v == tuple(P):
            p_index = i
        if v == tuple(Q):
            q_index = i
    print(abs(p_index-q_index))

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

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
c = []
for i in range(n):
    c.append(i+1)
l = []
for x in itertools.permutations(c,n):
    l.append(list(x))
l.sort()
p0 = 0
q0 = 0
for i in range(len(l)):
    if l[i] == p:
        p0 = i
    if l[i] == q:
        q0 = i
print(abs(p0-q0))

Submission status: Accepted

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

n = int(input())
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))
l = list(itertools.permutations(sorted(a)))
res1=0
res2=0
for i in range(len(l)):
    if l[i]==a:
        res1=i
    if l[i]==b:
        res2=i
print(abs(res1-res2))

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
if p == q:
    print(0)
    exit()
import itertools
def permutation_all(seq, choice):
    return list(itertools.permutations(seq, choice))
s = [i for i in range(1, n+1)]
s_p = permutation_all(s, n)
p = tuple(p)
q = tuple(q)
a = b = -1
for i in range(len(s_p)):
    if p == s_p[i]:
        a = i+1
    elif q == s_p[i]:
        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()))
lst = [i+1 for i in range(N)]
a = 0
b = 0
for i, l in enumerate(list(itertools.permutations(lst))):
    if (list(l) == P):
        a = i + 1
    if (list(l) == Q):
        b = i + 1
print(abs(a-b))

Submission status: Accepted

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

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

def index_p(i):
  return all_pat.index(i)+1

print(abs(index_p(P) - index_p(Q)))

Submission status: Accepted

Solution code:
import itertools


n = int(input())
p = [i+1 for i in range(n)]
x = list(itertools.permutations(p, n))
q = tuple(map(int, input().split()))
a = x.index(q)
q = tuple(map(int, input().split()))
b = x.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()))

count = 1
tmpp, tmpq = 0, 0
li = []

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

pattern = list(itertools.permutations(li))

for i in pattern:
    if i == p:
        tmpp = count

    if i == q:
        tmpq = count

    count += 1

print(abs(tmpp - tmpq))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from itertools import permutations
def main():
    n=int(input())
    pp=tuple(map(int,input().split()))
    qq=tuple(map(int,input().split()))
    res=[]
    for i, p in enumerate(permutations(list(range(1,n+1)))):
        if pp == p: 
            res.append(i+1)
        if qq == p:
            res.append(i+1)
        if len(res) == 2:
            print(abs(res[1]-res[0]))
            return

main()

Submission status: Accepted

Solution code:
# ABC150 C
si = lambda: input()
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: tuple(map(int, input().split()))
import itertools
n=ni()
p=nl()
q=nl()

if p==q:
    print(0)
    exit()
L=[]
for i in range(n):
    L.append(i+1)
a=0
b=0
idx=1
for l in list(itertools.permutations(L)):
    idx+=1
    if l==p:
        a=idx
    elif l==q:
        b=idx

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()))
A=[]
B=[]
a=0
b=0
for i in range(1,n+1):
  A.append(i)
  B.append(i)
for i in range(n):
  a=a+A.index(p[i])*math.factorial(n-i-1)
  A.remove(p[i])
for i in range(n):
  b=b+B.index(q[i])*math.factorial(n-i-1)
  B.remove(q[i])
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()))

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

ans = abs(R.index(P) - R.index(Q))
print(ans)

Submission status: Accepted

Solution code:
import itertools

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

x = sorted(itertools.permutations(list(range(1, n + 1))))
a = None
b = None
for i in range(len(x)):
    if p == x[i]:
        a = i
    if q == x[i]:
        b = i
    if a is not None and b is not None:
        break
print(abs(a - b))

Submission status: Accepted

Solution code:
from sys import stdin
from itertools import permutations
n = int(stdin.readline().rstrip())
ps = tuple(map(int, stdin.readline().rstrip().split()))
qs = tuple(map(int, stdin.readline().rstrip().split()))
a = 0
b = 0
per = permutations([i for i in range(1, n + 1)])
for i, v in enumerate(per):
    if ps == v:
        a = i
    if qs == v:
        b = i

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

def is_same(tpl, lst):
    for i in range(len(lst)):
        if tpl[i] != lst[i]:
            return False
    return True

# 整数の入力
n = int(input())
# スペース区切りの整数の入力
p_list_str = input().split(' ')
q_list_str = input().split(' ')

p_list = []

for item in p_list_str:
    p_list.append(int(item))
    
q_list = []

for item in q_list_str:
    q_list.append(int(item))

l = range(1, n+1)

iter_list = list(itertools.permutations(l))
a = 0
b = 0

for i in range(len(iter_list)):
    item = iter_list[i]
    if is_same(item, p_list):
        a = i
    if is_same(item, q_list):
        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()))
R=[]

for i in range(N):
    num = i+1
    R.append(num)

L=list(itertools.permutations(R))
S=[]
for i in range(len(L)):
    S.append(0)
    for j in range(N):
        S[i]+=L[i][j]*(10**(N-1-j))

S.sort()

p=0
q=0
for i in range(N):
        p+=P[i]*(10**(N-1-i))
        q+=Q[i]*(10**(N-1-i))
tmp1=0
tmp2=0
for i in range(len(S)):
    if S[i]==p:
        tmp1=i
    
    if S[i]==q:
        tmp2=i

print(abs(tmp1-tmp2))

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 = []
for x in permutations(range(1,N+1),N):
    A.append(list(x))
A = sorted(A)
indP = A.index(P)
indQ = A.index(Q)
print(abs(indP-indQ))

Submission status: Accepted

Solution code:
from itertools import permutations

n = int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
perms = list(permutations(range(1, n + 1)))
for i, perm in enumerate(perms):
    if all(x == y for x, y in zip(p, perm)):
        a = i
    if all(x == y for x, y in zip(q, perm)):
        b = i


print(abs(a - b))

Submission status: Accepted

Solution code:
import itertools

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

P_num=0
Q_num=0

li=[x for x in range(1,N+1)]
A=list(itertools.permutations(li))

for i in range(len(A)):
   if P==A[i]:
      P_num=i+1
   if Q==A[i]:
      Q_num=i+1

print(abs(P_num-Q_num))

Submission status: Accepted

Solution code:
import itertools

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

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

Submission status: Accepted

Solution code:
import itertools

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

p = sorted(itertools.permutations(P, N))
q = sorted(itertools.permutations(Q, N))

print(abs(p.index(P) - q.index(Q)))