Problem:


Score : 300 points

Problem Statement

We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).

There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.

Notes

For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.

Sample Input 2

8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0



Sample input:
3
1 3 2
3 1 2


Sample output:
3

Submission status: Accepted

Solution code:
import sys
import itertools

def main():
	
    # sys.stdin = open('input150c.txt')
	
    n = int(input())
    p = tuple(map(int, input().split()))
    q = tuple(map(int, input().split()))

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

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

    print(abs(a - b))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools

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

A = list(range(1, N + 1))
for i, x in enumerate(itertools.permutations(A)):
    if list(x) == P:
        pn = i
    if list(x) == Q:
        qn = i
print(abs(pn - qn))

Submission status: Accepted

Solution code:
import math


N = int(input())
list1 = list(map(int, input().split()))
list2 = list(map(int, input().split()))

def CO(l):
    n = len(l)
    if n != 1:
        m = sorted(l)
        a = l[0]
        s = m.index(a)
        l.remove(a)
        return((s)*math.factorial(n-1)+CO(l))
    else:
        return 1

print(abs(CO(list1)-CO(list2)))

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 = [i+1 for i in range(n)]
cnt = 0
for v in permutations(l, n):
    cnt += 1
    if v == P:
        p = cnt
    if v == Q:
        q = cnt
print(abs(p-q))

Submission status: Accepted

Solution code:

from math import factorial
def tempcalc(lst, N):
    templst = [i for i in range(1, N + 1)]
    ord = (lst[0] - 1) * factorial(N - 1) + 1
    templst.remove(lst[0])

    for i in range(N - 1):
        ord += (templst.index(lst[i + 1]) - 1) * factorial(N - i - 2)
        templst.remove(lst[i + 1])
    return ord

def CountOrder():
    N = int(input())
    P = []
    Q = []
    for _ in range(1):
        P = list(map(int, input().split()))
        Q = list(map(int, input().split()))


    ord = abs(tempcalc(P, N) - tempcalc(Q, N))

    print(ord)

CountOrder()

Submission status: Accepted

Solution code:
def factorial(n):
    return n * factorial(n - 1) if n > 0 else 1

def rank(P):
    N = len(P)
    r = list(range(N))
    result = 0
    for i in range(N):
        result += r[P[i]] * factorial(N - 1 - i)
        for j in range(P[i] + 1, N):
            r[j] -= 1
    return result

N = int(input())
P = list(map(lambda s: int(s) - 1, input().split()))
Q = list(map(lambda s: int(s) - 1, input().split()))

print(abs(rank(P) - rank(Q)))

Submission status: Accepted

Solution code:
import itertools

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


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

a=t.index(p)
b=t.index(q)
 
print(abs(a-b))

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
Factorial_list = [1,1]
for i in range(N-2):
    Factorial_list.append(Factorial_list[-1]*(i+2))
Factorial_list.reverse()
P_cnt = [0 for i in range(N)]
Q_cnt = [0 for i in range(N)]
for i in range(N):
    cnt = 0
    for j in range(i+1,N):
        if P[i]>P[j]:
            cnt+=1
    P_cnt[i]=cnt
for i in range(N):
    cnt = 0
    for j in range(i+1,N):
        if Q[i]>Q[j]:
            cnt+=1
    Q_cnt[i]=cnt
a = 0
b = 0
for i in range(N):
    a+=P_cnt[i]*Factorial_list[i]
    b+=Q_cnt[i]*Factorial_list[i]
if a-b>=0:
    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=1
for i in permutations(range(1,n+1),n):
    i=list(i)
    if i==p:
        a=cnt
    if i==q:
        b=cnt
    cnt+=1
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

N = int(input())

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

P = int(''.join(P))
Q = int(''.join(Q))

nums = []
for i in itertools.permutations(range(1, N + 1)):
    num = ''
    for j in i:
        num += str(j)
    num = int(num)
    nums.append(num)

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

Submission status: Accepted

Solution code:
# coding: utf-8

import math
import itertools

N = int(input())

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

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

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

a = b = 0
n_list = list(itertools.permutations(range(1, N + 1)))
n_list.sort()
for i, p in enumerate(n_list):
	if p == P:
		a = i
	if p == Q:
		b = i
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
X = list(itertools.permutations(range(1,N+1),N))

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

Submission status: Accepted

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

import itertools
X = list(itertools.permutations(range(1,N+1),N))
for i in range(len(X)):
  x = X[i]
  if P == x:
    a = i 
  if Q == x:
    b = i

print(abs(a-b))

Submission status: Accepted

Solution code:
def calc(D):
        global N
        global s
        n = list(range(1,N+1))
        v=0
        for i in range(N):
                p=n.index(D[i])
                v += s[N-i-1] * p
                n.pop(p)
        return v
        
N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
n = list(range(1,N+1))
s = [0]*(N+1)
s[0] = n[0]

for i in range(1,N+1): s[i] = s[i-1] * n[i-1]

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

Submission status: Accepted

Solution code:
N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
n = list(range(1,N+1))
s = [0]*(N+1)
s[0] = n[0]
for i in range(1,N+1): s[i] = s[i-1] * n[i-1]
vp=0
for i in range(N):
        p=n.index(P[i])
        vp += s[N-i-1] * p
        n.pop(p)
n = list(range(1,N+1))
vq=0
for i in range(N):
        p=n.index(Q[i])
        vq += s[N-i-1] * p
        n.pop(p)

print(abs(vp-vq))

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)))
print(abs((l.index(P)+1)-(l.index(Q)+1)))

Submission status: Accepted

Solution code:
import itertools

def main():
    N = int(input())
    P = tuple(map(int, input().split()))
    Q = tuple(map(int, input().split()))
    a = b = 0
    for i, p in enumerate(itertools.permutations(range(1, N+1))):
        if p == P:
            a = i
        if p == Q:
            b = i
    print(abs(a-b))
    

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

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

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
J=(list(itertools.permutations(range(1,n+1))))
#print(J)
for i, j in enumerate(J):
    #print(j,p,q)
    if j == p:
        a=i
    if j==q:
        b=i
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
lst = list(range(1, n + 1))
perm = list(itertools.permutations(lst, n))
ans = 0

for i in range(len(perm)):
    if perm[i] == p:
        ans += i
    if perm[i] == q:
        ans -= i

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

Submission status: Accepted

Solution code:
import itertools

N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
NA=NB=0

for i,j in enumerate(list(itertools.permutations(range(1,N+1)))):
  if list(j)==A:
    NA=i
  if list(j)==B:
    NB=i

print(abs(NA-NB))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = int("".join(input().split()))
S = int("".join(input().split()))

conb = list(itertools.permutations([str(i+1) for i in range(N)], N))
conb = sorted([int("".join(list(string))) for string in conb])

print(abs(conb.index(P) - conb.index(S)))

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc150/tasks/abc150_c
# TODO: try


def generate_pattern(pattern, current, n):
    c = current[:]
    remain = n - len(c)
    if remain > 0:
        for i in range(1, n + 1):
            if i not in c:
                c.append(i)
                generate_pattern(pattern, c, n)
                c.pop()
    else:
        pattern.append(c)


def main():
    n = int(input())
    array_a = [int(s) for s in input().split(" ")]
    array_b = [int(s) for s in input().split(" ")]
    pattern = []
    a = -1
    b = -1
    for i in range(n):
        generate_pattern(pattern, [i + 1], n)
    for i, v in enumerate(pattern):
        if array_a == v:
            a = i
        if array_b == v:
            b = i
        if a != -1 and b != -1:
            break
    print(abs(a - b))


def get_num(array, i, n):
    t = abs(array[i - 1] - (i - 1))
    t = t ** (n - i -1)
    return t


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
li = [i+1 for i in range(n)]
# print(p)
# print(q)

i = 0
for elm in itertools.permutations(li):
    #print(list(elm))
    if list(elm) == p:
        mm1 = i
    if list(elm) == q:
        mm2 = i
    i+=1
print(abs(mm1-mm2))

Submission status: Accepted

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


def main():
    from itertools import permutations

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

    ps = sorted((permutations(range(1, n + 1))))

    for index, pi in enumerate(ps, 1):
        if pi == p:
            a = index
        if pi == q:
            b = index

    print(abs(a - b))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#coding:utf-8
#全探索
import itertools
n = int(input())
#permutationすると各結果がタプルで返るので入力をタプルにする
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))

#全部の並べ替えパターンを列挙,ついでにソートしておく
pattern = sorted(list(itertools.permutations(p)))
#print(pattern)
print(abs(pattern.index(p) - pattern.index(q)))

Submission status: Accepted

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

def f(p):
    if len(p) == 1:
        return 1
    i = sorted(p).index(p[0])
    return factorial(len(p)-1)*i + f(p[1:])

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

Submission status: Accepted

Solution code:
import sys


def num_list(nums):
    if len(nums) == 1:
        return [nums]
    result = []
    for num in nums:
        next_nums = nums.copy()
        next_nums.remove(num)
        result += list(map(lambda x: [num] + x, num_list(next_nums)))
    return result


def solve(inp):
    N = int(inp.readline().strip())
    P = list(map(int, inp.readline().strip().split(' ')))
    Q = list(map(int, inp.readline().strip().split(' ')))

    nl = num_list(list(range(1, N + 1)))
    p = nl.index(P)
    q = nl.index(Q)

    return str(abs(p - q))


def main():
    result = solve(sys.stdin)
    if result:
        print(result)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools

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

lst = []
for i in itertools.permutations(range(1, n+1)):
    num = int(''.join(map(str, list(i))))
    lst.append(num)

num_p = int(''.join(map(str, p)))
num_q = int(''.join(map(str, q)))

for i in range(len(lst)):
    if lst[i] == num_p:
        arg_p = i
    if lst[i] == num_q:
        arg_q = i

print(abs(arg_q-arg_p))

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

n=int(input())
a=list(input().split())
b=list(input().split())
a="".join(a)
b="".join(b)
suuji=""
for i in range(1,n+1):
    suuji+=str(i)
info=[]
for i in itertools.permutations(suuji):
    new_i="".join(list(i))
    info.append(new_i)
a_index,b_index=0,0
for i in range(math.factorial(n)):
    if info[i]==a:
        a_index=(i+1)
    if info[i]==b:
        b_index=(i+1)
print(abs(a_index-b_index))

Submission status: Accepted

Solution code:
import numpy as np
import math
n = int(input())

#list(map(データ型, input().split))で入力された文字列を指定したデータ型に変換して、コンマ区切りのリストを作る
p_list = list(map(int, input().split()))
q_list = list(map(int, input().split()))


#np.array(リスト)とすることで、リスト型をNumpy配列に変換できる
p_np = np.array(p_list)
q_np = np.array(q_list)

pAnswer = 1
qAnswer = 1
for val in range(n):
	a = 0
	for va in range(0,val+1):
		if va != val : 
			if p_np[va] < p_np[val] :
				a += 1
			else :
				continue
		else:
			pAnswer += math.factorial(n - val -1) * (p_list[val] -1 -a)
			

for val in range(n):
	a = 0
	for va in range(0,val+1):
		if va != val : 
			if q_np[va] < q_np[val] :
				a += 1
			else :
				continue
		else:
			qAnswer += math.factorial(n - val -1) * (q_list[val] -1 -a)
			
print(abs(pAnswer - qAnswer))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
n = int(input())
string = str(1)
for i in range(2,n + 1):
    string += str(i)

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

for i,j in enumerate(x):
    if a == j:
        a_res = i + 1
    if b == j:
        b_res = i + 1

print(abs(a_res - b_res))

Submission status: Accepted

Solution code:
from itertools import permutations


def solve(string):
    n, *pq = map(int, string.split())
    *ps, = permutations(range(1, n + 1))
    return str(abs(ps.index(tuple(pq[n:])) - ps.index(tuple(pq[:n]))))


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))

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

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

Submission status: Accepted

Solution code:
import itertools
def resolve():
    n=int(input())
    p=tuple(map(int,input().split()))
    q=tuple(map(int,input().split()))
    l=list(range(1,n+1))
    chk=list(itertools.permutations(l))
    a=chk.index(p)
    b=chk.index(q)
    print(abs(a-b))

resolve()

Submission status: Accepted

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

from itertools import permutations

B=sorted(P)
PMT=list(permutations(B))

#print(PMT)
p=PMT.index(tuple(P))
q=PMT.index(tuple(Q))
print(abs(p-q))

Submission status: Accepted

Solution code:
import sys
import itertools

N = int(sys.stdin.readline())
P = [int(v) for v in sys.stdin.readline().split()]
Q = [int(v) for v in sys.stdin.readline().split()]
Ps = [list(v) for v in itertools.permutations(range(1, N + 1),N)]
Ps = sorted(Ps)

def find(l1):
    for i, l3 in enumerate(Ps):
        if l3 == l1:
            return i
    return 0

print(abs(find(P) - find(Q)))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
l = sorted(list(itertools.permutations([i for i in range(1,n+1)])))

al = tuple([int(i) for i in input().split()])
bl = tuple([int(i) for i in input().split()])


a,b = 0,0


if al == bl:
    print(0)
else:
    for idx,i in enumerate(l):
        if i == al:
            a = idx
        elif i == bl:
            b = idx
        else:
            pass
        
    print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import math

N = int(raw_input())
l = []
for i in range(1,N+1):
  l.append(i)
p = list(itertools.permutations(l))

P = tuple(raw_input().split())
P_i = [int(s) for s in P]
P_i = tuple(P_i)
con_p = 0
for i in range(len(p)):
  if p[i] == P_i:
    con_p = i
    break

Q = tuple(raw_input().split())
Q_i = [int(s) for s in Q]
Q_i = tuple(Q_i)
con_q = 0
for i in range(len(p)):
  if p[i] == Q_i:
    con_q = i
    break
print abs(con_p-con_q)

Submission status: Accepted

Solution code:
import math


# 数列が何番目かを返却するメソッド
def junban(N, str):
    int_list = str.split()  # 入力文字を配列化
    int_list = [int(i) for i in int_list]
    used_list = []
    num = 0
    for element in int_list:
        N -= 1
        used_count = 0
        for used in used_list:
            if element > used:
                used_count += 1
        num += (element - 1 - used_count) * math.factorial(N)
        used_list.append(element)
    # print(num)
    return num


# 大きさNを受け取る
N = int(input())
# 数列Pを受け取る
P = input()
# 数列Qを受け取る
Q = input()
# それぞれが何番目か求める
p_int = junban(N, P)
q_int = junban(N, Q)
print(abs(p_int - q_int))

Submission status: Accepted

Solution code:
# 問題文： 大きさ N の順列 ((1, 2, ..., N) を並び替えてできる数列) P, Q があります。大きさ N の順列は N! 通り考えられます。
#         このうち、P が辞書順で a 番目に小さく、Q が辞書順で b 番目に小さいとして、|a−b| を求めてください。
# 注記： 2 つの数列 X, Y について、ある整数 k が存在して Xi=Yi (1≤i<k) かつ Xk<Yk が成り立つとき、X は Y より辞書順で小さいと定義されます。
# 制約: 2≤N≤8　P,Qは大きさNの順列である。入力は全て整数である。

import math

# 数列が何番目かを返却するメソッド
def junban(N, str):
    int_list = str.split() # 入力文字を配列化
    int_list = [int(i) for i in int_list]
    yet_list = str.split() # まだ出てきていない数字のリスト
    yet_list = [int(i) for i in yet_list]

    num = 1 # 何番目か保持する
    keta = 0 # 上から何桁目か保持する

    while keta < N:
        # 該当桁の数字を確保する
        now_int = int_list[keta]

        # 未出数値のリストを更新する
        yet_list.remove(now_int)

        # 順番をカウント
        # 該当桁以下の階乗 * 未出数値の内、現在より数値の小さいものの個数
        num += math.factorial(len(yet_list)) * len([i for i in yet_list if i < now_int])
        keta += 1

#    print('{}番目'.format(num))
    return num

# 大きさNを受け取る
N = int(input())

# 数列Pを受け取る
P = input()

# 数列Qを受け取る
Q = input()

# それぞれが何番目か求める
p_int = junban(N, P)
q_int = junban(N, Q)

print(abs(p_int - q_int))

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
fact = [1]*n
for i in range(1, n):
  fact[i] = fact[i-1]*(i+1)

pl = [i+1 for i in range(n)]
ql = [i+1 for i in range(n)]

pn = 0
qn = 0
for i in range(n-1):
  pn += pl.index(p[i])*fact[n-i-2]
  qn += ql.index(q[i])*fact[n-i-2]
  pl.remove(p[i])
  ql.remove(q[i])
print(abs(pn-qn))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
l = list(range(1, n + 1))
ll = list(itertools.permutations(l, n))
if p == q:
    ans = 0
else:
    for i in ll:
        if i == p:
            p_n = ll.index(i) + 1
        elif i == q:
            q_n = ll.index(i) + 1
    ans = abs(p_n - q_n)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
import itertools
plist = list(itertools.permutations([i+1 for i in range(n)]))
count = 1
resultp = 0
resultq = 0
for pp in plist:
    if(list(pp) == p):
        resultp = count
    if (list(pp) == q):
        resultq = count
    count += 1
print(abs(resultp - resultq))

Submission status: Accepted

Solution code:
# 問題文： 大きさ N の順列 ((1, 2, ..., N) を並び替えてできる数列) P, Q があります。大きさ N の順列は N! 通り考えられます。
#         このうち、P が辞書順で a 番目に小さく、Q が辞書順で b 番目に小さいとして、|a−b| を求めてください。
# 注記： 2 つの数列 X, Y について、ある整数 k が存在して Xi=Yi (1≤i<k) かつ Xk<Yk が成り立つとき、X は Y より辞書順で小さいと定義されます。
# 制約: 2≤N≤8　P,Qは大きさNの順列である。入力は全て整数である。

import math

# 数列が何番目かを返却するメソッド
def junban(N, str):
    int_N = int(N)
    int_list = str.split() # 入力文字を配列化
    int_list = [int(i) for i in int_list]
    yet_list = str.split() # まだ出てきていない数字のリスト
    yet_list = [int(i) for i in yet_list]

    num = 1 # 何番目か保持する
    keta = 0 # 上から何桁目か保持する

    while keta < (int_N):
        # 該当桁の数字を確保する
        now_int = int_list[keta]

        # 未出数値のリストを更新する
        yet_list.remove(now_int)

        # 該当桁以下の階乗
   #     print('該当桁以下の桁数は：{}'.format(len(yet_list)))
        # 該当桁の数字より若い数字がいくつ残っているか
    #    print('該当桁の数字より若い数字はあと{}個'.format(len([i for i in yet_list if i < now_int])))

        # 順番をカウント
        # 該当桁以下の階乗 * 未出数値の内、現在より数値の小さいものの個数
        num += math.factorial(len(yet_list)) * len([i for i in yet_list if i < now_int])
        keta += 1

#    print('{}番目'.format(num))
    return num

# 大きさNを受け取る
N = input()
# 数列Pを受け取る
P = input()
# 数列Qを受け取る
Q = input()

# Pが何番目か求める
p_int = junban(N, P)
q_int = junban(N, Q)

print(abs(p_int - q_int))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
lists = set(range(1, n+1))
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
cnt = 0
for i in itertools.permutations(lists, n):
    cnt += 1
    if i == p:
        p_num = cnt
    if i == q:
        q_num = cnt
print(abs(p_num-q_num))

Submission status: Accepted

Solution code:
def fractorial(m):
    ans = 1
    for i in range(1,m):
        ans*=i
    if m==0:
        ans=1
    return ans

n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
list_nump = list(range(1,n+1))
list_numq = list(range(1,n+1))
rank_p = 0
rank_q = 0
for i in range(n):
    tmp_frac = fractorial(n-i)
    rank_p += (list_nump.index(p[i]))*tmp_frac
    list_nump.remove(p[i])
    rank_q += (list_numq.index(q[i]))*tmp_frac
    list_numq.remove(q[i])
print(abs(rank_p-rank_q))

Submission status: Accepted

Solution code:
import itertools
n=int(input())
p=[str(i) for i in input().split()]
p=','.join(p)
p=p.replace(",", "")
q=[str(i) for i in input().split()]
q=','.join(q)
q=q.replace(",", "")

r='1'
for i in range(2,n+1):
  r+=str(i)

List = []

for x in itertools.permutations(r):
  y=','.join(x)
  y=y.replace(",", "")
  List.append(y)
  
P=List.index(p)
Q=List.index(q)
print(abs(P-Q))

Submission status: Accepted

Solution code:
N = int(input())
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]

import itertools

p_index = 0
q_index = 0
base_list = sorted(P)
for i, v in enumerate(itertools.permutations(base_list, N)):
    v = list(v)
    if P == v:
        p_index = i
    if Q == v:
        q_index = i

print(abs(p_index-q_index))

Submission status: Accepted

Solution code:
import itertools
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
perms = []
for i in itertools.permutations([j+1 for j in range(n)]):
    perms.append(list(i))
perms.sort()
for i in range(len(perms)):
    if perms[i]==p:
        rp = i
    if perms[i] ==q:
        rq = i
print(abs(rq-rp))

Submission status: Accepted

Solution code:
import itertools

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

base = list(range(1, n+1))

for i, v in enumerate(itertools.permutations(base, n)):
    if v == p:
        p_id = i+1
    if v == q:
        q_id = i+1

print(abs(p_id - q_id))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
a = [i+1 for i in range(n)]

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

ans = []
for i, v in enumerate(itertools.permutations(a, n)):
    if list(v) == p or list(v) == q:
        ans.append(i)
    if len(ans) == 2:
        print(ans[1] - ans[0])
        exit()
print(0)

Submission status: Accepted

Solution code:
import itertools

N = int(input())

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

a = -1
b = -1

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

print(abs(a - b))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from itertools import permutations as pr

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

fir = sorted(list(pr(p)))
sec = sorted(list(pr(q)))

for i in range(len(fir)):
    fir[i] = list(fir[i])
    sec[i] = list(sec[i])

a = fir.index(p)
b = sec.index(q)

print(abs(a-b))

Submission status: Accepted

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

Submission status: Accepted

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

s = []
for i in range(N):
  s.append(i+1)
p_list = list(itertools.permutations(s))

p_n = 0
q_n = 0
for i in range(len(p_list)):
  if p == p_list[i]:
    p_n = i
  if q == p_list[i]:
    q_n = i
    
print(p_n - q_n) if p_n >= q_n else print(q_n - p_n)

Submission status: Accepted

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

n = int(input().rstrip())
P = [int(x) for x in input().rstrip().split()]
Q = [int(x) for x in input().rstrip().split()]
cnt = [1 if i > 0 else 0 for i in range(0, n + 1)]
fact = [1]
for i in range(1, n+1):
    fact.append(fact[i-1] * i)

ord_P = 0
for i in range(0, n):
    cnt[P[i]] -= 1
    ord_P += sum(cnt[:P[i]+1]) * fact[n - i - 1]

ord_Q = 0
cnt = [1 if i > 0 else 0 for i in range(0, n + 1)]
for i in range(0, n):
    cnt[Q[i]] -= 1
    ord_Q += sum(cnt[:Q[i]+1]) * fact[n - i - 1]

print(abs(ord_P - ord_Q))

Submission status: Accepted

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

l = 0
r = 0

for i, j in enumerate(itertools.permutations(range(1,N+1)), start=1):
    if j == P and j == Q:
        l, r = i, i
    elif j == P:
        l = i
    elif j == Q:
        r = i
    else:
        pass

print(abs(l-r))

Submission status: Accepted

Solution code:
import sys
import math
import heapq
from itertools import permutations
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
DVSR = 1000000007
def POW(x, y): return pow(x, y, DVSR)
def INV(x, m=DVSR): return pow(x, m - 2, m)
def DIV(x, y, m=DVSR): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()
def II(): return int(input())
def FLIST(n):
    res = [1]
    for i in range(1, n+1): res.append(res[i-1]*i%DVSR)
    return res
def gcd(x, y):
    if x < y: x, y = y, x
    div = x % y
    while div != 0:
        x, y = y, div
        div = x % y
    return y

N=II()

DIC = list(permutations(list(range(1, N+1)), N))
a=DIC.index(tuple(LI()))
b=DIC.index(tuple(LI()))

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
i = int(input())
s=list(range(1, i+1))
ss=list(itertools.permutations(s))
l1,l2=tuple(map(int, input().split())),tuple(map(int, input().split()))
l1c,l2c=0,0
for i, sss in enumerate(ss):
  if sss == l1:
    l1c=i+1
  if sss == l2:
    l2c=i+1
    
print(abs(l1c-l2c))

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 = 0
b = 0
for i, perm in enumerate(permutations(range(1, n+1))):
    if perm == p:
        a = i
    if perm == q:
        b = i
print(abs(a-b))

Submission status: Accepted

Solution code:
n=int(input())
#s=list(input().split())
#s,t=list(input().split())
#a=list(map(int,input().split()))
#k,x=map(int,input().split())
p=list(input().split())
q=list(input().split())
p=[int(i) for i in p]
q=[int(i) for i in q]
import itertools
import math
p_index,q_index=0,0
fulllist=list(itertools.permutations([i for i in range(1,n+1)]))
for i in range(math.factorial(n)):
    if p==list(fulllist[i]):
        p_index=i+1
    if q==list(fulllist[i]):
        q_index=i+1
print(abs(p_index-q_index))

Submission status: Accepted

Solution code:
import sys
import itertools
MAX_INT = int(10e12)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N = I()
p = IL()
q = IL()
a = [i for i in range(1,N+1)]

data = list(itertools.permutations(a))
data.sort()

for i in range(len(data)):
  if p == list(data[i]):
    pp = i
  if q == list(data[i]):
    qq = i
print(abs(pp - qq))

Submission status: Accepted

Solution code:
def main():
    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)))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

    perm = list(itertools.permutations(range(1,n+1)) )
    ansp = perm.index(tuple(p))
    # qq = list(itertools.permutations(q) )
    ansq = perm.index(tuple(q))

    print(abs(ansp-ansq))

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import itertools
N = int(input())
p = "".join(input().split())
q = "".join(input().split())

cnt = 1
for x in itertools.permutations(range(1, N + 1)):
    tmp = "".join(map(str, x))
    if p == tmp:
        a = cnt
    if q == tmp:
        b = cnt
    cnt += 1

print(abs(a-b))

Submission status: Accepted

Solution code:
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
import itertools
li=[i for i in range(1,n+1)]
cnt=0
a=-1
for x in itertools.permutations(li):
    x=list(x)
    if x==p or x==q:
        if a>=0:
            print(abs(cnt-a))
            exit()
        else:
            a=cnt    
    cnt+=1                
print(0)