Problem:


Score : 300 points

Problem Statement

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

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

Notes

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

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

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

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

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

Sample Input 2

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

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0



Sample input:
3
1 3 2
3 1 2


Sample output:
3

Submission status: Accepted

Solution code:
import itertools

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

C = list(itertools.permutations(R, N))

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

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


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

p = itertools.permutations(l, n)
ans_a = 0
ans_b = 0
count = 0

for i in p:
    if i == a:
        ans_a = count
    if i == b:
        ans_b = count
    count += 1

print(abs(ans_b-ans_a))

Submission status: Accepted

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

import itertools
all=[]
seq=list(range(1,n+1))
for ptn in itertools.permutations(seq):
  all.append(list(ptn))

ans=abs(all.index(p)-all.index(q))

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
L = [i+1 for i in range(N)]
R = [i+1 for i in range(N)]
A,B = 0,0
for i in range(N-1):
    A *= N-i
    B *= N-i
    A += L.index(P[i])
    B += R.index(Q[i])
    L[L.index(P[i])] = 100
    R[R.index(Q[i])] = 100
    L.sort()
    R.sort()
print(abs(A-B))

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
num=[str(i+1) for i in range(n)]
nums=sorted([int("".join(i)) for i in permutations(num,n)])
P=int("".join(map(str,input().split())))
Q=int("".join(map(str,input().split())))
a,b=0,0
for j,i in enumerate(nums):
    if i==P:a=j
    if i==Q:b=j
print(abs(a-b))

Submission status: Accepted

Solution code:
# coding: utf-8
from itertools import permutations
N = int(input())
P = list(map(str, input().split()))
Q = list(map(str, input().split()))

l = list(permutations(P))
l.sort()
ll = []
for i in range(len(l)):
    a = list(map(str, l[i]))
    ll.append("".join(a))
p_idx = ll.index("".join(P))
q_idx = ll.index("".join(Q))
print(abs(p_idx - q_idx))

Submission status: Accepted

Solution code:
from itertools import permutations
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
ln = []
for i in range(1, n + 1):
    ln.append(i)
pn = list(permutations(ln))
sorted_pn = sorted(pn)

# print(sorted_pn)

a = sorted_pn.index(p) + 1
b = sorted_pn.index(q) + 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()))

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

def nasu(L):
  ans = 1
  K = [0] * (N + 1)
  for i in range(N):
    t = i + 1
    k = 0
    for j in range(1, N + 1):
      if L[i] == j: break
      if K[j] == 0:
        k += 1
    K[L[i]] = 1
    ans += k * D[N - t]
  return ans

print(abs(nasu(P) - nasu(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()))

S = [n for n in range(1, N+1)]
a = 0
b = 0

for i, p in enumerate(list(permutations(S))):
    if p == P:
        a = i + 1
    if p == Q:
        b = i + 1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
P = tuple(P)
Q = tuple(Q)
pm = list(itertools.permutations(list(range(1, N+1))))

a = 0
b = 0

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

print(abs(a-b))

Submission status: Accepted

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

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

a=lst.index(p)+1
b=lst.index(q)+1
print(abs(a-b))

Submission status: Accepted

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

from itertools import permutations

arr = list()
for i in permutations(list(range(1, N + 1)), N):
    arr.append(''.join([str(x) for x in i]))

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

Submission status: Accepted

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

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

Per = list(itertools.permutations(n_list))
for i in range(len(Per)):
 tmp = list(Per[i])
 judge1,judge2 = 1,1
 for j in range(len(tmp)):
  if(tmp[j] != P[j]):
    judge1 = 0
  if(tmp[j] != Q[j]):
    judge2 = 0
    
 if(judge1 == 1): a = i+1
 if(judge2 == 1): b = i+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()))

a = list(itertools.permutations([i+1 for i in range(n)], n))
ans = 0
for i in range(len(a)):
    if a[i]==p:
        ans+=i+1
    if a[i]==q:
        ans-=i+1
print(abs(ans))

Submission status: Accepted

Solution code:
import itertools

N=int(input())
P=[int(i) for i in input().split(" ")]
Q=[int(i) for i in input().split(" ")]
for i,perm in enumerate(itertools.permutations([i+1 for i in range(N)])):
    if list(perm)==P:
        a=i
    if list(perm)==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()))
if p == q:
    print(0)
else:
    l = list(itertools.permutations(range(1,n+1)))
    p_i = l.index(p)
    q_i = l.index(q)
    print(abs(p_i-q_i))

Submission status: Accepted

Solution code:
import sys
import itertools
import math
input = sys.stdin.readline
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
jisyo=[]
for i in range(1,N+1):
    jisyo.append(i)
ans =[]
for v in itertools.permutations(jisyo, N):
    ans.append(list(v))
print(abs(ans.index(P)-ans.index(Q)))

Submission status: Accepted

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

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

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

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

Pnum=-1
Qnum=-1

for i,item in enumerate(L):
  if item==P:
    Pnum=i
  if item==Q:
    Qnum=i
  if Pnum>-1:
    if Qnum >-1:
      break

      
print(abs(Pnum-Qnum))

Submission status: Accepted

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

def gcd(a: int, b: int):
    """ https://cocodrips.hateblo.jp/entry/2014/03/05/143623
    """
    while b:
        a, b = b, a%b
    return a

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


def main():
    N = int(input())
    #K,X = map(int, input().split())
    vP = tuple(map(int, input().split()))
    vQ = tuple(map(int, input().split()))
    vA = list(range(1,N+1))

    p,q = 0,0
    for i,vI in enumerate(permutations(vA)):
        #print(i,vI)
        #if i==7: break
        if vI==vP:
            p = i
        if vI==vQ:
            q = i
    print(abs(p-q))
    #S = input().rstrip()
    #print(S)
    #print(lcm(N, M))
    #print("Yes" if X<=500*K else "No")
    #print(S.count("ABC"))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())

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

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

x = ans.index(p)+1
y = ans.index(q)+1

if x -y >=0:
    print(x-y)
elif x-y < 0:
    print(y-x)

Submission status: Accepted

Solution code:
import itertools

N=int(input())
X=tuple(map(int,input().split()))
Y=tuple(map(int,input().split()))
#print(X)

L=[i for i in range(1,N+1)]
A=list(itertools.permutations(L,N))
A.sort()
x=0
y=0
for i in range(len(A)):
    if A[i]==X:
        x=i
    if A[i]==Y:
        y=i
#print(A)
#print(x,y)
print(abs(x-y))

Submission status: Accepted

Solution code:
def two_int():
    N, K = map(int, input().split())
    return N,K

def one_int():
    return int(input())

def one_str():
    return input()

def many_int():
    return list(map(int, input().split()))

import itertools as it

N= one_int()
P= many_int()
Q= many_int()

temp = list(set(P))
ans_list = list(it.permutations(temp))



first=ans_list.index(tuple([p for p in P]))

after=ans_list.index(tuple([q for q in Q]))

print(abs(after-first))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = "".join(input().split())
Q = "".join(input().split())
L = []
for p in itertools.permutations(map(str, range(1,N+1))):
    L.append("".join(p))
L.sort()
p = -1
q = -1
i = 0
for elem in L:
    if P == elem:
        p = i
    if Q == elem:
        q = i
    i+=1
ans = abs(q-p)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools

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

seq=(i for i in range(1,N+1))
All=list(itertools.permutations(seq))

for i in range(len(All)):
    if All[i]==P:
        start=i
    if All[i]==Q:
        end=i

print(abs(end-start))

Submission status: Accepted

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

for i, lst in enumerate(itertools.permutations(range(1,N+1))):
    if lst == P:
        p = i
    if lst == Q:
        q = i
print(abs(p-q))

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
aa=()
import itertools
c=list(itertools.permutations(range(1,n+1)))
cc=[]
for i in c:
    cc.append(list(i))
for x,i in enumerate(cc):
    if a==i:
        aa=x
    if b==i:
        bb=x
print(abs(aa-bb))

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 = range(1, n+1)
t, u = 0, 0
for i, s in enumerate(permutations(a)):
    if s == p: t = i
    if s == q: u = i

print(abs(t - u))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int , input().split()))
q = list(map(int , input().split()))
idx = 1
a = 0
b = 0
for x in itertools.permutations(list(range(1, n+1)), n):
    if tuple(p) == x:
        a = idx
    if tuple(q) == x:
        b = idx
    idx += 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

diff = 0
n2i = {n: i for i, n in enumerate(itertools.permutations(range(1, N + 1)))}
print(abs(n2i[P] - n2i[Q]))

Submission status: Accepted

Solution code:
from itertools import permutations
fact = [1]
N = int(input())
seq = [i for i in range(1, N+1)]
seq = list(permutations(seq))
dic = {}
for i in range(len(seq)):
  x = seq[i]
  dic[x] = i
p = tuple([int(c) for c in input().split()])
q = tuple([int(c) for c in input().split()])

P = dic[p]
Q = dic[q]
print(abs(P-Q))

Submission status: Accepted

Solution code:
from itertools import permutations as pe
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
d=list([list(i)for i  in pe([i for i in range(1,n+1)],n)])
print(abs(d.index(q)-d.index(p)))

Submission status: Accepted

Solution code:
from itertools import permutations

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

ans = 0

for i, pe in enumerate(permutations(range(1, N + 1))):
    if P == pe:
        ans += i
    if Q == pe:
        ans -= i

print(abs(ans))

Submission status: Accepted

Solution code:
import itertools

# 引数のリストの全ての順列リストを返す
def fact_list(seq:list):
    return list(itertools.permutations(seq))


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

x = fact_list(range(1, n+1))
a = 0
b = 0
for i, xi in enumerate(x):
    if list(xi) == P:
        a = i+1
    if list(xi) == Q:
        b = i+1
print(abs(a-b))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = [1]
for i in range(n-1):
  c = [c[0]*(i+1)] + c
#print(c)
A = 0
for i in range(n):
  now = a[i]
  cnt = 0
  for k in range(i+1,n):
    if a[k] < now:
      cnt += 1
  A += c[i] * cnt
B = 0
for i in range(n):
  now = b[i]
  cnt = 0
  for k in range(i+1,n):
    if b[k] < now:
      cnt += 1
  B += c[i] * cnt
print(abs(A-B))

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

a, b = -1, -1
for i, p in enumerate(permutations(range(1, N + 1), N), 1):
    if list(p) == P:
        a = i
    if list(p) == Q:
        b = i
    if a >= 1 and b >= 1:
        break

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

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

a = b = 1

for l in L:
    if l == P:
        break
    a += 1
for l in L:
    if l == Q:
        break
    b += 1
print(abs(a-b))

Submission status: Accepted

Solution code:
import sys
import itertools
import math
#import numpy as np

stdin = sys.stdin

ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split())) # applies to numbers only
rs = lambda: stdin.readline().rstrip()  # ignore trailing spaces

N = ri()
P = rl()
Q = rl()
L = []
for x in itertools.permutations(range(1, N+1)):
    L.append(list(x))
a = 0
b = 0
for i in range(math.factorial(N)):
    if L[i] == P:
        a = i
    if L[i] == 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()))

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

Submission status: Accepted

Solution code:
import itertools

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

N = [str(x) for x in range(1, n+1)]
All = []
for y in itertools.permutations(N):
    moji = ''
    for z in y:
        moji += z
    All.append(moji)

All = sorted(All)
p = ''
q = ''
for x in P:
    p += str(x)
for x in Q:
    q += str(x)

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

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()])
li = [0] * N
for i in range(N) :
    li[i] = i+1
import itertools
from itertools import permutations
c = list(itertools.permutations(li))
a = 0
b = 0
for i in range(len(c)) :
    if c[i] == P :
        a = i
    if c[i] == Q :
        b = i
print(abs(b-a))

Submission status: Accepted

Solution code:

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

from itertools import permutations

L = list((range(1, N+1)))

M = sorted(list(permutations(L, N)))

len_m = len(M)

a = -1
b = -1

for i in range(len_m):
  pSame = True
  qSame = True
  for j in range(N):
    if M[i][j] != P[j]:
      pSame = False
    if M[i][j] != Q[j]:
      qSame = False
  
  if pSame:
    a = i
  if qSame:
    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()))

a, b = 0, 0
perms = sorted(permutations(list(range(1, n+1))))
for i, perm in enumerate(perms):
  if p == perm:
    a = i+1
  if q == perm:
    b = i+1
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = ''.join([x for x in input().split()])
Q = ''.join([x for x in input().split()])
D = {}
for i, s in enumerate(sorted(itertools.permutations((str(n) for n in range(1, N + 1))))):
  D[''.join(s)] = i
print(abs(D[P] - D[Q]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
import itertools
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


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

    f = -1
    s = -1

    for i, perm in enumerate(itertools.permutations(range(1, n + 1))):
        if perm == p:
            f = i
        if perm == q:
            s = i

    print(abs(f - s))


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import math
import itertools
import fractions
import heapq
import collections
import bisect
import sys

sys.setrecursionlimit(10**9)
mod = 998244353
inf = 10**20

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()

n = I()
p = LI()
q = LI()

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

l = [i for i in range(1,n+1)]
a=0
b=0
for i,x in enumerate(itertools.permutations(l)):
    if p==list(x):
        a = i
    if q==list(x):
        b = i
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

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

#print(buf)

a=buf.index(tuple(p))+1
b=buf.index(tuple(q))+1

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()]
F=[1]
for i in range(8):
  F.append(F[-1]*(i+1))

a=1
b=1
def num(A,x):
  for i in range(len(A)):
    if A[i]==x:
      return i
N=[int(i) for i in range(1,n+1)]
M=[int(i) for i in range(1,n+1)]
for i in range(n):
  a+=num(N,P[i])*F[n-i-1]
  b+=num(M,Q[i])*F[n-i-1]
  N.remove(P[i])
  M.remove(Q[i])
print(abs(a-b))

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n=I()
  p=LI()
  q=LI()

  a=[i+1 for i in range(n)]
  ansa=0
  ansb=0
  for j,x in enumerate(itertools.permutations(a)):
    f1=True
    f2=True
    for i in range(n):
      if x[i]!=p[i]:
        f1=False
      if x[i]!=q[i]:
        f2=False
    if f1:
      ansa=j+1
    if f2:
      ansb=j+1

  # print(ansa,ansb)
  return abs(ansa-ansb)

# main()
print(main())

Submission status: Accepted

Solution code:
import math
import bisect
import collections
import itertools
import heapq
import string
import sys
sys.setrecursionlimit(10**9)
def gcd(a,b):return math.gcd #最大公約数
def lcm(a,b):return (a*b) // math.gcd(a,b) #最小公倍数
def iin(): return int(input()) #整数読み込み
def isn(): return input().split() #文字列読み込み
def imn(): return map(int, input().split()) #整数map取得
def iln(): return list(map(int, input().split())) #整数リスト取得
def iln_s(): return sorted(iln()) # 昇順の整数リスト取得
def iln_r(): return sorted(iln(), reverse=True) # 降順の整数リスト取得
def join(l, s=''): return s.join(l) #リストを文字列に変換
def perm(l, n): return itertools.permutations(l, n) # 順列取得
def perm_count(n, r): return math.factorial(n) // math.factorial(n-r) # 順列の総数
def comb(l, n): return itertools.combinations(l, n) # 組み合わせ取得
def comb_count(n, r): return math.factorial(n) // (math.factorial(n-r) * math.factorial(r)) #組み合わせの総数
def divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i: divisors.append(n//i)
    return divisors
def is_prime(n):
    if n == 1: return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0: return False 
    return True
def primes(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n + 1, i): is_prime[j] = False
    return [i for i in range(n+1) if is_prime[i]]
def sieve_of_e(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n+1, i): is_prime[j] = False
    return is_prime

N = iin()
P = iln()
Q = iln()

PS = sorted(list(perm(P,N)))

p = 0
q = 0
for i in range(len(PS)):
    if P == list(PS[i]):
        p = i
    if Q == list(PS[i]):
        q = i
print(abs(p-q))

Submission status: Accepted

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

from itertools import permutations

sort_P = list(permutations(sorted(P)))

answer = 0
for i,x in enumerate(sort_P):
    if list(x) == P:
        answer += i + 1
    if list(x) == Q:
        answer -= i + 1

print(abs(answer))

Submission status: Accepted

Solution code:
# coding:utf-8
import itertools

N = int(input())
P = tuple(map(int, input().split(' ')))
Q = tuple(map(int, input().split(' ')))
pnum = 0
qnum = 0

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

for idx, el in enumerate(itertools.permutations(l, N)):
    if el == P:
        pnum = idx + 1
    if el == Q:
        qnum = idx + 1
    if pnum != 0 and qnum != 0:
        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()))
seq=list(range(1,n+1))
l=list(itertools.permutations(seq))
p_i=l.index(p)
q_i=l.index(q)
print(abs(p_i-q_i))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools


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

R = sorted(P)

for index, S in enumerate(list(itertools.permutations(R))):
    PS = sum([P[n] != S[n] for n in range(N)])
    QS = sum([Q[n] != S[n] for n in range(N)])
    if PS == 0:
        index_P = index
    if QS == 0:
        index_Q = index

print(abs(index_P - index_Q))

Submission status: Accepted

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

Submission status: Accepted

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

    per = list(itertools.permutations(tuple(range(1,N+1))))
    
    i = 0
    a = 0
    b = 0
    for p in per:
        if p == P:
            a = i
        if p == Q:
            b = i
        i += 1
    
    print(abs(a-b))

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import itertools

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

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

# print(l)
prm = list(itertools.permutations(l))
# print(prm)

a = None
b = None
for i in range(len(prm)):
    s = ' '.join(str(c) for c in prm[i])
    if s == p:
        a = i+1
    if s == q:
        b = i + 1

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

Submission status: Accepted

Solution code:
def f(n):
    if n == 1:
        return 1
    return f(n - 1) * n


n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
l = list(range(1, n + 1))
a = 0
for i, x in enumerate(p[:-1]):
    a += l.index(x) * f(n - i - 1)
    l.remove(x)
b = 0
l = list(range(1, n + 1))
for i, x in enumerate(q[:-1]):
    b += l.index(x) * f(n - i - 1)
    l.remove(x)
print(abs(b - a))

Submission status: Accepted

Solution code:
from sys import stdin
import itertools
#stdin = open("input.txt")

if __name__ == "__main__":
  N = int(stdin.readline())
  P = tuple([int(i) for i in stdin.readline().split()])
  Q = tuple([int(i) for i in stdin.readline().split()])
  # print(P, Q)

  for i, perm in enumerate(sorted(list(itertools.permutations(range(1, 1+N))))):
    # print(perm)
    if perm == P:
      indexP = i
    if perm == Q:
      indexQ = i

  print(abs(indexP-indexQ))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
seq = [i for i in range(1,n+1)]
p = list(map(int, input().split()))
q = list(map(int, input().split()))
p = tuple(p)
q = tuple(q)
a = list(itertools.permutations(seq))
ans = [0,0]
for i in range(len(a)):
    if a[i]==p:
        ans[0] = i+1

    if a[i] ==q:
        ans[1] = i+1
print(abs(ans[0]-ans[1]))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

all = []
for i in range(N):
    all.append(i+1)

p_list = list(itertools.permutations(all, N))


def check_eq(A, B):
    flag = True
    for i in range(len(A)):
        if A[i] == B[i]:
            pass
        else:
            flag = False
            break
    return flag

a_num = 0
b_num = 0
for i in range(len(p_list)):
    if check_eq(p_list[i], A):
        a_num = i + 1
    if check_eq(p_list[i], B):
        b_num = i + 1
print(abs(a_num - b_num))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = ''.join(input().split())
q = ''.join(input().split())
ans = 0
for i, a in enumerate(itertools.permutations('12345678' [:n], n)):
    s = ''.join(a)
    if p == s:
        ans += i
    if q == s:
        ans -= i
print(abs(ans))

Submission status: Accepted

Solution code:
N=int(input())
P=list(map(int,input().split()))
ps=""
for i in range(N):
  ps+=str(P[i])
Q=list(map(int,input().split()))
qs=""
for i in range(N):
  qs+=str(Q[i])

stack=[]
stack.append("")
res=[]
while stack:
  d=stack.pop()
  if len(d)==N:
    res.append(d)
    continue
  for i in range(1,N+1):
    if str(i) not in d:
      stack.append(d+str(i))
  
res=res[::-1]
a=0
b=0
for i in range(len(res)):
  if res[i]==ps:
    a=i+1
  if res[i]==qs:
    b=i+1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

a = 0
for _ in itertools.permutations(range(N)):
    if not(_ > Q) and not(_ < Q):
        break
    a += 1

b = 0
for _ in itertools.permutations(range(N)):
    if not(_ > P) and not(_ < P):
        break
    b += 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()))

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

per = list(itertools.permutations(nums,r = N))

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