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:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
import time
from bisect import bisect_left, insort_left, bisect_right
import sys
import random
import itertools

input = sys.stdin.readline
_NUMINT_ALL = list(range(10))
_START_TIME = time.time()


def main():
    ans = solve()

    if ans is True or ans is False:
        YesNo(ans)
    elif ans is not None:
        print(ans)


def solve():
    N = iip()[0]
    P = iip()
    Q = iip()

    np = 1
    nq = 1

    for p in itertools.permutations(range(N)):
        #print(p)
        for i, s in enumerate(p):
            if s+1 != P[i]:
                break
        else:
            break
        np += 1

    for q in itertools.permutations(range(N)):
        #print(q)
        for i, s in enumerate(q):
            if s+1 != Q[i]:
                break
        else:
            break
        nq += 1

    #print(np)
    #print(nq)

    return abs(np-nq)



#####################################################ライブラリ集ここから




def kiriage_warizan(a, b):
    return -(-a//b)


def iip(listed=True):  # 数字のinputをlistで受け取る
    d = input().rstrip("\n").split()
    try:
        ret = [int(i) for i in d]
    except:
        ret = [int(i) if i in _NUMINT_ALL else i for i in d]
        if len(ret) == 1 and listed is False:
            return ret[0]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret

def iipt(l, listed=True, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed))
    return ret


def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m

def time_debug_10percent():
    a = random.randint(0, 9)
    if a == 9:
        sys.exit()

def time_debug(t):
    time.sleep(_START_TIME + t - time.time())
    sys.exit()


def make_graph_edge_flat(N):  # グラフ作成のための辺をリストで返す
    ret = []
    for i in range(N-1):
        a, b, c = iip()
        a -= 1
        b -= 1
        ret[a].append((b, c))
        ret[b].append((a, c))
    return ret


def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))


def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)


def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)


def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


def nibutan_func(func, target, left, right, side="left"): # 関数を二分探索
    l = left
    r = right
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if func(x) == target:
            return x
        elif func(x) > target:
            r = x
        else:
            l = x

    if side == "left" or func(x) == target:
        return l
    else:
        return r


def nibutan_list(list_, target, side="left"):  # リストを二分探索
    if not isinstance(list_, list):
        list_ = list(list_)

    l = 0
    r = len(list_)
    x = (l + r) // 2
    while r-l > 1:
        x = (l+r)//2
        if list_[x] == target:
            return x
        elif list_[x] > target:
            r = x
        else:
            l = x

    if side == "left" or list_[x] == target:
        return l
    else:
        return r


class UfTree():
    def __init__(self, maxnum):
        self.parent = list(range(maxnum))
        self._size = [1] * maxnum
        self.rank = [0] * maxnum

    def size(self, a):
        return self._size[self.root(a)]

    def root(self, a):
        rank = 0
        cur = a
        while True:
            if self.parent[cur] == cur:
                #for i in path: # 経路圧縮
                #    self.parent[i] = cur
                return cur
            else:
                self.parent[cur] = self.parent[self.parent[cur]]
                cur = self.parent[cur]
                rank += 1

    def unite(self, a, b):
        ra = self.root(a)
        rb = self.root(b)
        if ra == rb:
            return self

        self._size[ra] += self._size[rb]
        self.parent[rb] = ra
        return self

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

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

a, b = 0, 0

for i, v in enumerate(s, start=1):
	if v == p:
		a = i
	elif v == q:
		b = i
	else:
		pass

print(0) if p == q else print(abs(a - b))

Submission status: Accepted

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

fact = [1] * 8
for i in range(1,8):
    fact[i] = fact[i-1] * i

a = 0
remain = list(range(1,N+1))

for i , v  in enumerate(P):
    num = remain.index(v)
    remain.remove(v)
    a += num * fact[(N - i - 1)]

b = 0
remain = list(range(1,N+1))

for i , v  in enumerate(Q):
    num = remain.index(v)
    remain.remove(v)
    b += num * fact[(N - i - 1)]

print(abs(b-a))

Submission status: Accepted

Solution code:
import itertools
N = str(input())
P = ''.join(list(map(str, input().split())))
Q = ''.join(list(map(str, input().split())))
l=[]
for v in itertools.permutations(P):
    l.append(''.join(v))
print(abs(sorted(l).index(P)-sorted(l).index(Q)))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
P = "".join(list(input().split()))
Q = "".join(list(input().split()))

Z = [(0,"",[0]*N)]
A = []
while Z:
    z = Z.pop(0)
    if z[0]==N:
        A.append(z[1])
        continue
    for i in range(N):
        if z[2][i]==0:
            zz = z[2][::]
            zz[i]=1
            Z.append((z[0]+1,z[1]+str(i+1),zz))
A.sort()
a,b = 0,0
for i in range(len(A)):
    if A[i]==P:
        a = i
    if A[i]==Q:
        b = i
print(abs(a-b))

Submission status: Accepted

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

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()]
for i, l in enumerate(permutations(range(1, n+1)), 1):
  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 = list(map(int,input().split()))
q = list(map(int,input().split()))
f = list(map(lambda x:list(x),list(itertools.permutations([i+1 for i in range(n)],n))))
print(abs(f.index(p) - f.index(q)))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# AtCoder Beginner Contest 150
# C - Count Order
# https://atcoder.jp/contests/abc150/tasks/abc150_c

from itertools import permutations

N = int(input())
P = tuple(i-1 for i in map(int, input().split()))
Q = tuple(i-1 for i in map(int, input().split()))

F = list(permutations(range(N)))

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#パクリ
import itertools

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

lis=list(itertools.permutations(P))
lis.sort()

#indexで要素の何番目か取得
print(abs(lis.index(P)-lis.index(Q)))

Submission status: Accepted

Solution code:
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)]
a = 0
b = 0

#順列作成
L_list = list(itertools.permutations(L))

for i in range(len(L_list)):
  if list(L_list[i]) == P:
    a = i+1
  if list(L_list[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()))

L = [i for i in range(1, N+1)]
a = 0
b = 0

#順列作成
L_list = list(itertools.permutations(L))

for i in range(len(L_list)):
  if list(L_list[i]) == P:
    a = i+1

for i in range(len(L_list)):
  if list(L_list[i]) == Q:
    b = i+1
#  else:
#    continue

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
def ii():return int(input())
def iim():return map(int,input().split())
def iil():return list(map(int,input().split()))
def ism():return map(str,input().split())
def isl():return list(map(str,input().split()))

n = ii()
l = list(itertools.permutations(range(1,n+1)))
#print(type(l[0]))
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
#print(a,b)
print(abs(l.index(a)-l.index(b)))

'''
n = ii()
ans = []
def DFS(head, rest):
    if len(rest) == 0:
        print('hoge')
        ans.append(head)
        rest.append(head.pop(-1))
        return 0
    else:
        print('foo')
        head.append(rest.pop(0))
        DFS(head, rest)
        tmp = head[-1]
        head[-1] = rest[-1]
        rest[-1] = tmp


d = []
DFS(d,list(range(1,n+1)))
print(d)
'''

Submission status: Accepted

Solution code:
import itertools

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

A = list(itertools.permutations(range(1,N+1)))
cnt_a = 0
cnt_b = 0
for i in range(len(A)):
  if P == A[i]:
    cnt_a += i
  if Q == A[i]:
    cnt_b += i

print(abs(cnt_a - cnt_b))

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)]
for n,t in enumerate(itertools.permutations(l,N)):
    if(t==P):
        a=n
    if(t==Q):
        b=n

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

l=range(1,n+1)

a=0

b=0

cnt=0

for i in itertools.permutations(l,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 = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))

l = list(range(1,n+1))
dic = {}

for i,j in enumerate(itertools.permutations(l)):
    dic[j] = i+1
print(abs(dic[p]-dic[q]))

Submission status: Accepted

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

arr = list(itertools.permutations(seq))
print(abs(arr.index(p) - arr.index(q)))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import itertools
l = list(range(1, int(input()) + 1))
p = list(map(int, input().split()))
q = list(map(int, input().split()))
cnt_a = 1
cnt_b = 1
for i in itertools.permutations(l):
    if list(i) == p:
        a = cnt_a
    if list(i) == q:
        b = cnt_b
    cnt_a += 1
    cnt_b += 1
print(abs(a - b))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
c = []
for i in range(1,n+1):
	c.append(i)

p_list = list(itertools.permutations(c))
ans = abs(p_list.index(a) - p_list.index(b))
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from itertools import permutations as pe
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
l = [i for i in range(1, N+1)]
p, q = 0, 0
for i,j  in enumerate(pe(l)):
    if j==P:
        p = i+1
    if j==Q:
        q = i+1
print(abs(p-q))

Submission status: Accepted

Solution code:
from itertools import permutations

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

a = 0
b = 0
for i, iter in enumerate(permutations(range(1, N+1))):
    if iter == P:
        a = i
    if iter == 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()))
for i, pi in enumerate(permutations(range(1, n+1))):
    if pi == p:
        a = i
    if pi == 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()))
U = list(itertools.permutations(range(1, N+1)))
a = U.index(P)
b = U.index(Q)
print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations
import sys
import heapq
from collections import Counter
from collections import deque
from fractions import gcd
from math import factorial
from math import sqrt
INF = 1 << 60
sys.setrecursionlimit(10 ** 6)

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


#ここから書き始める
n = int(input())
x = [i for i in range(1, n + 1)]
p = list(map(int, input().split()))
q = list(map(int, input().split()))
a = 0
b = 0
cnt = 0
a_finished = False
b_finished = False
for i in permutations(x):
    # print("i =", i)
    if a_finished and b_finished:
        break
    if list(i) == p:
        a = cnt
        a_finished = True 
    if list(i) == q:
        b = cnt
        b_finished = True
    cnt += 1
ans = abs(a - b)
print(ans)

Submission status: Accepted

Solution code:
import itertools
n = int(input())
plis = list(map(int, input().split()))
qlis = list(map(int, input().split()))
lis = list(itertools.permutations(range(1, n+1)))
n = 1
for i in lis:
    if list(i) == plis:
        a = n
    if list(i) == qlis:
        b = n
    n += 1
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()))

dig=[1]*(N+1)
dig[0]=0
a=1
for i,pp in enumerate(p):
    a+=sum(dig[:pp])*math.factorial(N-i-1)
    dig[pp]=0

dig=[1]*(N+1)
dig[0]=0
b=1
for i,qq in enumerate(q):
    b+=sum(dig[:qq])*math.factorial(N-i-1)
    dig[qq]=0
print(abs(a-b))

Submission status: Accepted

Solution code:
import os
from itertools import permutations

def main():
	p_score, q_score, count = 0,0,0
	string = ""
	num = int(input())
	p_num = tuple(list(map(str, input().split())))
	q_num = tuple(list(map(str, input().split())))
	for i in range(1,num+1):
		string  = string + str(i) 
	list_ = list(permutations(string, num))
	
	for i in list_:

		count += 1
		if p_num == i:
			q_score = count
		if q_num == i:
			p_score = count
	
		
	print(abs(q_score - p_score))
		


if __name__ == '__main__':
	main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools
n = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
p = list(itertools.permutations(range(1, n + 1)))
a = p.index(P)
b = p.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()))
num = []
for i in range(1,n+1):
    num.append(i)
ans = []
for i in list(itertools.permutations(num)):
    ans.append(i)
print(abs(ans.index(P)-ans.index(Q)))

Submission status: Accepted

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

n_perm = [i for i in range(1, n + 1)]
n_perm = permutations(n_perm)
cnt = 0
for x in n_perm:
    if x == p: a = cnt
    if x == q: b = cnt
    cnt += 1
print(abs(a - b))

Submission status: Accepted

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

cnt=0
for v in itertools.permutations(range(1,n+1), n):
    cnt +=1
    if(p==v):
        a = cnt
    if(q==v):
        b = cnt

print(abs(a-b))

Submission status: Accepted

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

for i, v in enumerate(itertools.permutations(range(1,n+1))):
    if p==v:
        s=i
    if q==v:
        t=i
print(abs(s-t))

Submission status: Accepted

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

num = []
for i in range(1,n+1):
    num.append(i)
ans = []
for i in itertools.permutations(num,n):
    ans.append(i)

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
input = sys.stdin.buffer.readline
def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def LI(): return list(map(int,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode('utf-8')
#import numpy as np

from itertools import permutations


def main():
	n=II()
	P=TI()
	Q=TI()
	ans=0
	for i,p in enumerate(permutations(range(1,n+1),n)):
		if P==p:
			ans-=i
		if Q==p:
			ans+=i
	print(abs(ans))




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

x = list(range(N))
x = [y+1 for y in x]
p = itertools.permutations(x)
a=None
b=None
cnt = 1
for l in p:
    if list(l) == P:
        a = cnt
    if list(l) == Q:
        b = cnt
    if a!=None and b!=None:
        print(abs(a-b))
        exit()
    cnt += 1

Submission status: Accepted

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

import itertools

A = list(range(1, N + 1))
L = []

for i in itertools.permutations(A, N):
    L.extend([list(i)])

for index, value in enumerate(L):
    if L[index] == P:
        p = index
    if L[index] == Q:
        q = index

print(abs(p - q))

Submission status: Accepted

Solution code:
import itertools


def main():
    N = [i for i in range(1, int(input()) + 1)]
    P = tuple(map(int, input().split(' ')))
    Q = tuple(map(int, input().split(' ')))
    x, y = 0, 0
    for enum, n in enumerate(itertools.permutations(N)):
        if n == P:
            x = enum + 1
        if n == Q:
            y = enum + 1
        if x > 0 and y > 0:
            break
    print(abs(x - y))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

from itertools import permutations

li=[]
for i in permutations(A, n):
    li.extend([list(i)])
    
for i, v in enumerate(li):
    if li[i] == p:
        s = i
    if li[i] == q:
        t = i
print(abs(s-t))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools

N = int(input())

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

p = list(itertools.permutations(l, N))

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

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

print(abs(b-a))

Submission status: Accepted

Solution code:
from itertools import permutations

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

comb = list(permutations(range(1, N+1)))
ans = abs(comb.index(P) - comb.index(Q))

print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations as per
n, *w = map(int, open(0).read().split())
l = list(per(range(1, n+1)))
def F(_):
  return l.index(tuple(_))
print(abs(F(w[:n]) - F(w[n:])))

Submission status: Accepted

Solution code:
# 初期入力
N = int(input())
S = [tuple(map(str, input().split())) for i in range(2)]

from itertools import permutations
kaijo =[str(i) for i in range(1,N+1)]
junretu = [t for t in permutations(kaijo) ]
nanbannme_1 =junretu.index(S[0])
nanbannme_2 =junretu.index(S[1])
print(abs(nanbannme_1 - nanbannme_2))
"""
print(nanbannme_1)
print(nanbannme_2)
print(junretu)
print(S)
"""

Submission status: Accepted

Solution code:
from itertools import permutations

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

    x = list(permutations(range(1,N+1),N))
    x.sort()
    p =0
    q =0
    for i,v in enumerate(x):
        if P == v:
            
            p = i
        if Q == v:
            
            q = i
    print(abs(p-q))


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
import math

n = int(input())
arraya = list(map(int,input().split()))
numsa = [i+1 for i in range(n)]
arrayb = list(map(int,input().split()))
numsb = [i+1 for i in range(n)]

cnta = 1
for i in range(n):
  num = arraya[i]
  mae = numsa.index(num)
  ushiro = math.factorial(n-(i+1))
  cnta += mae*ushiro
  numsa.remove(num)
  
cntb = 1
for i in range(n):
  num = arrayb[i]
  mae = numsb.index(num)
  ushiro = math.factorial(n-(i+1))
  cntb += mae*ushiro
  numsb.remove(num)
  
print(abs(cnta-cntb))

Submission status: Accepted

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

import sys
# import math
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from fractions import gcd                    # for Python3.4.3
from itertools import permutations

def main():
    mod = 10000007                  # 10^9+7
    inf = float('inf')
    input = sys.stdin.readline      # 改行文字が残ることに注意
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def ii():  return int(input())
    def mi():  return map(int, input().rstrip().split())
    def lmi(): return list(map(int, input().rstrip().split()))
    def li():  return list(input().rstrip())
    
    n = ii()
    p = tuple(mi())
    q = tuple(mi())
    perm = list(permutations(range(1, n+1))) 
    num_p = perm.index(p)
    num_q = perm.index(q)
    print(abs(num_p - num_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 = list(permutations(range(1, n+1)))
print(abs(perm.index(p) - perm.index(q)))

Submission status: Accepted

Solution code:
N= int(input())
p = input().replace(" ","")
q = input().replace(" ","")
kai = [1]
for i in range(2,N):
    kai.append(kai[-1]*i)
def calc(s,N):
    count =0
    nlist = [str(i) for i in range(1,N+1)]
    for i in range(N-1):
        
        idx = nlist.index(s[i])
        nlist.remove(s[i])
        count += (idx)*(kai[len(nlist)-1])
        
    return count+1

print(abs(calc(p,N)-abs(calc(q,N))))

Submission status: Accepted

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

a = list()
for i in range(1,n+1):
    a.append(int(i))
b = copy.copy(a)

kai = 1
for i in range(1,n+1):
    kai = kai * i

pans = 0
qans = 0
for i in range(n):
    kai = kai / (n-i)
    pans +=  kai * ( a.index(p[i]) + 1 )
    a.remove(p[i])
    
    qans +=  kai * ( b.index(q[i]) + 1 )
    b.remove(q[i])

print(int(abs(pans - qans)))

Submission status: Accepted

Solution code:
def yu(a):
    n = len(a)
    used = [False for i in range(n)]
    fact = 1
    ans = 0
    for i, x in enumerate(a[::-1]):
        cur = 0
        for y in range(x):
            if used[y]:
                cur += 1
        ans += cur * fact
        fact *= (i + 1)
        used[x-1] = True
    return ans
        

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(abs(yu(a) - yu(b)))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = list(map(int, input().split(" ")))
Q = list(map(int, input().split(" ")))
a, b = 0, 0

for i, perm in enumerate(itertools.permutations(range(N))):
    if all([p1 == (p2 + 1) for p1, p2 in zip(P, perm)]):
        a = i
    if all([p1 == (p2 + 1) for p1, p2 in zip(Q, perm)]):
        b = i

print(abs(a - b))