Problem:


Score : 300 points

Problem Statement

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

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

Notes

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

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

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

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

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

Sample Input 2

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

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0



Sample input:
3
1 3 2
3 1 2


Sample output:
3

Submission status: Accepted

Solution code:
import math

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

a = 1
b = 1
Pmin = sorted(P)
Qmin = sorted(Q)

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

for i in range(N-1) :
  Qorder = Qmin.index(Q[i])
  b += Qorder * math.factorial(N - i - 1)
  Qmin.pop(Qorder)

ans = a-b

if a-b >= 0 :
  print(ans)
else :
  print(-1 * ans)

Submission status: Accepted

Solution code:
import itertools

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

all_list = list(itertools.permutations(p))
all_list.sort()

p_ans = 0
q_ans = 0

for i in range(len(all_list)):
    if list(all_list[i]) == p:
        p_ans = i
    if list(all_list[i]) == q:
        q_ans = i
print(abs(p_ans - q_ans))

Submission status: Accepted

Solution code:
import itertools

N=int(input())
first=""
for i in range(N):
    first+=str(i+1)
P=tuple(map(str,input().split()))
Q=tuple(map(str,input().split()))

A=list(itertools.permutations(first))

p=A.index(P)
q=A.index(Q)

print(abs(p-q))

Submission status: Accepted

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

def f(x):
    if x == 0:
        return 1
    if x == 1:
        return x
    else:
        return x * f(x-1)

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

po = 0
for i in range(n):
    po += f(n-i-1)*nlist.index(p[i])
    nlist.remove(p[i])
po+=1
nlist = list(range(1, n+1))
qo = 0
for i in range(n):
    qo += f(n-i-1)*nlist.index(q[i])
    nlist.remove(q[i])
qo+=1
print(abs(po-qo))

Submission status: Accepted

Solution code:
import itertools
import math

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

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

for i in range(math.factorial(N)):
  if list(l[i]) == p:
    a = i
    break
    
for i in range(math.factorial(N)):
  if list(l[i]) == q:
    b = i
    break

print(abs(a-b))

Submission status: Accepted

Solution code:
def dictionary_order(Xs, n):
  ascend = [i+1 for i in range(n)]

  order = 1
  for i, x in enumerate(Xs):
    order += ascend.index(x) * factorial(n-1-i)
    ascend.remove(x)
  return order

def factorial(n):
  out = 1
  for i in range(2, n+1):
    out *= i
  return out

def main():
  N = int(input())
  Ps = list(map(int, input().split()))
  Qs = list(map(int, input().split()))
  if Ps == Qs:
    print(0)
  else:
    P_order = dictionary_order(Ps, N)
    Q_order = dictionary_order(Qs, N)
    print(abs(P_order-Q_order))
  
if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import math

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

p = 0
nf = math.factorial(N)
X = [False]*N
for i in range(N):
    nf //= (N-i)
    x = X[:P[i]].count(True)
    p += nf * (P[i]-1-x)
    X[P[i]-1] = True

q = 0
nf = math.factorial(N)
X = [False]*N
for i in range(N):
    nf //= (N-i)
    x = X[:Q[i]].count(True)
    q += nf * (Q[i]-1-x)
    X[Q[i]-1] = True

print(abs(p-q))

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)

l = list(range(1, n+1))
m = itertools.permutations(l,len(l))
_list = []
for i in m:
    _list.append(i)
print(abs(_list.index(p)-_list.index(q)))

Submission status: Accepted

Solution code:
import math
N = int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]

P = 0
Q = 0
for i in range(N-1):
    cnt_p = 0
    cnt_q = 0
    for j in range(i+1, N):
        if p[i] > p[j]:
            cnt_p += 1
        if q[i] > q[j]:
            cnt_q += 1
    P += cnt_p*math.factorial(N-1-i)
    Q += cnt_q*math.factorial(N-1-i)
print(abs(P-Q))

Submission status: Accepted

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

B = input().split(' ')
B = [int(j) for j in B]

string=""

for i in range (1,N+1):
    string+=str(i)

def permutation(lst): 
    if len(lst) == 0: 
        return [] 
    if len(lst) == 1: 
        return [lst] 
    l = []
    for i in range(len(lst)): 
       m = lst[i] 
       remLst = lst[:i] + lst[i+1:] 
       for p in permutation(remLst): 
           l.append([m] + p) 
    return l 

data = list(string)
permut_int=[]

for p in permutation(data): 
    permut_int.append([int(i) for i in p])

A_index = permut_int.index(A)+1
B_index = permut_int.index(B)+1

print(abs(A_index-B_index))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
a = list(range(1,n+1))
p = list(map(int, input().split()))
q = list(map(int, input().split()))
i = 1
ap = 0
aq = 0
for x in list(itertools.permutations(a)):
    if(list(x) == p):
        ap = i
    if(list(x) == q):
        aq = i
    i = i + 1

if(ap > aq):
    print(ap - aq)
    exit()
print(aq - ap)

Submission status: Accepted

Solution code:
import math
import itertools

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

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

Submission status: Accepted

Solution code:
import itertools

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

nn=[]
ss=[]

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

for i in itertools.permutations(nn):
    ss.append(''.join(map(str,list(i))))

ss.sort()

ai=ss.index(a)+1
bi=ss.index(b)+1

print(abs(ai-bi))

Submission status: Accepted

Solution code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def swap(a, i, j):
    tmp = a[i]
    a[i] = a[j]
    a[j] = tmp

def next_permutation(a):
    n = len(a)
    if n == 0 or n == 1:
        return False
    kFound = False
    for k in reversed(range(n - 1)):
        if a[k] < a[k + 1]:
            kFound = True
            break
    if not kFound:
        return False

    for l in reversed(range(n)):
        if a[k] < a[l]:
            break
    swap(a, k, l)
    return a[:k + 1] + [i for i in reversed(a[k + 1:])]

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
a = []
for i in range(1,n+1):
    a.append(i)
flag = 0
s = 0
t = 0
u = 1
while flag < 2:
    if p == a:
        s = u
        flag += 1
    if q == a:
        t = u
        flag += 1
    a = next_permutation(a)
    u += 1
if s - t >= 0:
    print(s - t)
else:
    print(t - s)

Submission status: Accepted

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

def Fac(n):
    if n == 1:
        return 1
    else:
        return n * Fac(n-1)

def answer(P):
    l = list(range(1, len(P)+1))
    ans = 0
    for pi in P:
        if len(l) <= 2:
            ans += sum([i<pi for i in l])+1
            break
        else:
            ans += sum([i<pi for i in l]) * Fac(len(l)-1)
            l.remove(pi)
    return ans

print(abs(answer(P)-answer(Q)))

Submission status: Accepted

Solution code:
import itertools

N = input()
P = input()
Q = input()
string1 = tuple(map(int, list(P.split(" "))))
string2 = tuple(map(int, list(Q.split(" "))))

num =list(itertools.permutations(list(range(1, int(N)+1))))
count = 1

for i in num:
    if i == string1:
        a = count
    if i == string2:
        b = count
    count += 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()))
P=["abcdefgh"[i-1] for i in p]
Q=["abcdefgh"[i-1] for i in q]
P=tuple(P)
Q=tuple(Q)
import itertools
R=list(itertools.permutations("abcdefgh"[:n]))
print(abs(R.index(P)-R.index(Q)))

Submission status: Accepted

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

l = list(range(1, n+1))
ll = []

def Count_Order(n, s):
    if n == 0:
        ll.append("".join(list(map(str, s))))
    else:
        for x in l:
            if not x in s:
                Count_Order(n-1, s+[x])

s = []
Count_Order(n, s)
print(abs(ll.index("".join(p)) - ll.index("".join(q))))

Submission status: Accepted

Solution code:
import itertools
#標準出力
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))

#ソートした
Psotred  = sorted(P)
Qsotred  = sorted(Q)

#順列造った。
A = list(itertools.permutations(Psotred, N))
B = list(itertools.permutations(Qsotred, N))

#taple型に変更した
P_tap = tuple(P)
Q_tap = tuple(Q)

ans_P = 1
ans_Q = 1

for i in A:
    if i != P_tap:
        ans_P = ans_P +1
    elif i == P_tap:
        break

for i in B:
    if i != Q_tap:
        ans_Q = ans_Q +1
    elif i == Q_tap:
        break
        
print(abs((ans_Q)-(ans_P)))

Submission status: Accepted

Solution code:
import itertools

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

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

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

L = list(itertools.permutations(l))

tp_ind = L.index(tp)
tq_ind = L.index(tq)

ans = (tp_ind+1) - (tq_ind+1)
print(abs(ans))

Submission status: Accepted

Solution code:
import math
A=[]
B=[]
n=int(input())
for i in range(n):
    A.append(i+1)
    B.append(i+1)
SA=set(A)
SB=set(B)
F=[1,1]
f=1
for i in range(n-2):
    f*=i+2
    F.append(f)
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
p=0
for i in range(n-1):
    p+=(list(SA).index(P[i]))*F[n-i-1]
    s=[]
    s.append(P[i])
    SA^=set(s)
q=0
for i in range(n-1):
    q+=(list(SB).index(Q[i]))*F[n-i-1]
    s=[]
    s.append(Q[i])
    SB^=set(s)
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()))
lp = list(permutations(p, n))
lq = list(permutations(q, n))
lp.sort()
lq.sort()
a=lp.index(p)
b=lq.index(q)
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
n = int(input())

ps = list(map(int,input().split()))

qs = list(map(int,input().split()))


a = 0
b = 0
r = 0
for i in range(n):
    if ps[i] == qs[i]:
        continue
    else:
        r = i
        break

ts = ps[r:]
ts.sort()

ns = list(itertools.permutations(ts))
m = len(ns)

for j in range(m):
    if list(ns[j]) == ps[r:]:
        a = j
        break

for l in range(m):
    if list(ns[l]) == qs[r:]:
        b = l
        break
    

print(abs(a-b))

Submission status: Accepted

Solution code:
"""
https://atcoder.jp/contests/abc150/tasks/abc150_c
"""
import numpy as np
from itertools import permutations


def calc(N: int, P: np.ndarray, Q: np.ndarray) -> int:
    pairs = list(permutations(range(1, N + 1)))
    pairs_dict = {tuple(v): i for i, v in enumerate(pairs)}
    return abs(pairs_dict[tuple(P)] - pairs_dict[tuple(Q)])


def load_input_as_int_array() -> np.ndarray:
    return np.array([int(v) for v in input().split(" ")])


def main() -> None:
    N, = load_input_as_int_array()
    P = load_input_as_int_array()
    Q = load_input_as_int_array()
    result = calc(N, P, Q)
    print(result)


main()

Submission status: Accepted

Solution code:
import itertools
import sys
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
a=[]
for i in range(1,n+1):
    a.append(i)
c=tuple(p)
d=tuple(q)
cnt=0
ans=0
ansl=0
if c==d:
    print(0)
    sys.exit()
for i in itertools.permutations(a):
    
    if c==i:
        ans=cnt
    elif d==i:
        ansl=cnt
    cnt+=1
print(abs(ans-ansl))

Submission status: Accepted

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

def ranking(n, numbers):
  tmp = list(range(1, n+1))
  ranking = []
  for n in numbers:
    index = tmp.index(n)
    ranking.append(index+1)
    tmp.pop(index)
  return ranking

def ranking2output(n, ranking):
  ret = 1
  x = 1
  for i in range(1, n+1):
    ret += (ranking[n-i]-1)*(x)
    x *= i
  return ret

a = ranking2output(n, ranking(n, p))
b = ranking2output(n, ranking(n, q))

print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations

n = int(input())
Ps = list(map(int, input().split()))
Qs = list(map(int, input().split()))

a = 0
b = 0

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

for v in permutations(Rs, n):
    v_s = ''.join(list(map(str, v)))
    p_s = ''.join(list(map(str, Ps)))
    
    if v_s == p_s:
        break
    else:
        a += 1

for v in permutations(Rs, n):
    v_s = ''.join(list(map(str, v)))
    q_s = ''.join(list(map(str, Qs)))
    
    if v_s == q_s:
        break
    else:
        b += 1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

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

x = [list(i) for i in itertools.permutations(r)]
  
if x.index(p) >= x.index(q):
  ans = x.index(p) - x.index(q)
else:
  ans = x.index(q) - x.index(p)

print(ans)

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = str(input().replace(' ', ''))
q = str(input().replace(' ', ''))

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

l2 = []
for i in l:
    youso = ''
    for j in range(n):
        youso += str(i[j])
    l2.append(youso)
    
p_n = l2.index(p)
q_n = l2.index(q)

print(abs(p_n-q_n))

Submission status: Accepted

Solution code:
import itertools

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

perm = list(itertools.permutations(range(1, N+1)))
a = perm.index(P)
b = perm.index(Q)

print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
l = list(permutations(range(1, n+1))) 
s1=[int(x) for x in input().split()]
s2=[int(x) for x in input().split()]
# print(l)
# print(s1)
# print(s2)
pos1=l.index(tuple(s1))
pos2=l.index(tuple(s2))
# print(pos1,pos2)
print(abs(pos1-pos2))

Submission status: Accepted

Solution code:
import math
import itertools
a = int(input())
b = map(int,input().split(' '))
c = map(int,input().split(' '))
x = []
d = 0
e = 0
b = tuple(b)
c = tuple(c)
for i in range(a):
    x.append(i + 1)
y = itertools.permutations(x)
j = 1
for i in y:
    if i == b:
        d = j
    if i == c:
        e = j
    j += 1
print(abs(d - e))

Submission status: Accepted

Solution code:
import math
import random
import itertools
N=int(input())
P=[int(x) for x in input().split()]
S=[int(x) for x in input().split()]

r=random.sample(range(1, N+1), k=N)
#p = itertools.permutations(r, N)
#print(r,p)
a=[]
p=0
s=0
for i in range(N):
    p+=P[i]*10**(N-i-1)
    s+=S[i]*10**(N-i-1)
for v in itertools.permutations(r, N):
    c=0
    for j in range(N):

        c+=v[j]*10**(N-j-1)
    a.append(c)
a.sort()
pin=a.index(p)
sin=a.index(s)
print(abs(pin-sin))

Submission status: Accepted

Solution code:
import itertools

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

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

P = ''.join(map(str,P))
Q = ''.join(map(str,Q))

num = 0
count = 1
A = 0
B = 0

for i in itertools.permutations(n):
  num = ''.join(map(str,i))
  if num == P:
    A = count
  if num == Q:
    B = count
  count += 1
  
print(abs(B-A))

Submission status: Accepted

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

def fact(n):
  if n == 1: return 1
  return n*fact(n-1)

def p_count(n, s, nums):
  if isinstance(nums, int):
    return 1
  idx=nums.index(s[0])
  nums.pop(idx)
  if len(nums) != 0:
    return (idx) * fact(n-1) + p_count(n-1, s[1:], nums)
  else:
    return 1
  
nl1=list(range(1,n+1))
nl2=list(range(1,n+1))
print(abs(p_count(n, p, nl1)-p_count(n, q, nl2)))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
data = range(1,N+1)
p_list = list(itertools.permutations(data, N))

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

P_num = 0
Q_num = 0

for index,data in enumerate(p_list):
  if list(data) == P:
    P_num = index
  if list(data) == Q:
    Q_num = index
    
print(abs(P_num - Q_num))

Submission status: Accepted

Solution code:
import itertools
def main():
    N = int(input())
    P = list(map(int, input().split()))
    S = list(map(int, input().split()))
    count = 1
    if P == S:
        print(0)
    else:
        for i in itertools.permutations(list(range(1,N + 1))):
            if P == list(i):
                a = count
            elif S == list(i):
                b = count
            count += 1
        print(abs(a - b))
main()

Submission status: Accepted

Solution code:
import itertools
def main():
    n=int(input())
    P=tuple(map(int,input().split()))
    Q=tuple(map(int,input().split()))
    L=[i for i in range(1,n+1)]
    S=itertools.permutations(L,n)
    ans=0
    flag=1
    i=0
    if P==Q:
        print(0)
        exit()
    for s in S:
        i+=1
        if s==P or s==Q:
            if flag:
                ans -= i
                flag =0
            else:
                ans += i
                break
    print(ans)
main()

Submission status: Accepted

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

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

a = 1
for i in range(N-1):
    idx = l.index(P[i])
    a += idx * factorial(N-1-i)
    del l[idx]
    
b = 1
for i in range(N-1):
    idx = ll.index(Q[i])
    b += idx * factorial(N-1-i)
    del ll[idx]
    
print(abs(a-b))

Submission status: Accepted

Solution code:
from math import factorial

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

for i in range(N-2):
  a += (P[i]-1-len([s for s in P[:i] if s < P[i]]))*factorial(N-i-1)
if P[N-2]>P[N-1]: a+=1

for i in range(N-2):
  b += (Q[i]-1-len([s for s in Q[:i] if s < Q[i]]))*factorial(N-i-1)  
if Q[N-2]>Q[N-1]: b+=1  
  
print(max(a,b)-min(a,b))

Submission status: Accepted

Solution code:
import itertools as it
a = int(input())
l = tuple(list(map(int,input().split())))
L = tuple(list(map(int,input().split())))
# print(l)
t = range(1,a+1)
T = list(it.permutations(t))
# print(T)
ans = abs (T.index(l)-T.index(L) )
print(ans)

Submission status: Accepted

Solution code:
import math
import itertools

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

nara = []
for v in itertools.permutations(list(range(1,N+1)), N):
  nara.append(list(v))

Pcount = nara.index(P)
Qcount = nara.index(Q)
print(abs(Pcount-Qcount))

Submission status: Accepted

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

def solve(x):
    if(x==1):
        return 1
    else:
        return x*solve(x-1)

def solve2(ls):
    x=ls[0]
    data=sorted(ls)
    return data.index(x)


ans1=0
ans2=0
for i in range(1,n):
    ans1+=solve(n-i)*solve2(p)
    del p[0]

    ans2+=solve(n-i)*solve2(q)
    del q[0]

print(abs(ans1-ans2))

Submission status: Accepted

Solution code:
import itertools

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

a = 0
b = 0
cnt = 0

tmp = sorted(P)

for x in itertools.permutations(tmp):
    cnt += 1

    if P == list(x):
        a = cnt

    if Q == list(x):
        b = cnt

print(abs(a - b))

Submission status: Accepted

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

r = []
for z in list(itertools.permutations(a, n)):
    r.append(z)
print(abs((r.index(p)+1)-((r.index(q)+1))))

Submission status: Accepted

Solution code:
from collections import deque
def main():
    N = int(input())
    P = [str(int(n)-1) for n in input().split()]
    Q = [str(int(n)-1) for n in input().split()]
    P = "".join(P)
    Q = "".join(Q)
    q = deque([str(i) for i in range(N)])
    i = 0
    while len(q) > 0:
        i += 1
        s = q.popleft()
        if s == P:
            pp = i
        if s == Q:
            qq = i
        if len(s) == N:
            continue
        for i in range(N):
            if str(i) not in s:
                q.append(s + str(i))
    print(abs(pp-qq))
main()

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
import itertools
R = []
for i in range(1,N+1):
    R.append(i)
H = list(itertools.permutations(R))
a = 0
b = 0
for i in range(len(H)):
    h = H[i]
    r = []
    for j in range(N):
        r.append(h[j])
    if r == P:
        a = i
    if r == Q:
        b = i
ans = max(a-b,b-a)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
fact=[1]*13
for i in range(2,13):
	fact[i]=i*fact[i-1]
p=list(map(int,input().split()))
q=list(map(int,input().split()))
a=0
b=0
for i in range(n):
	a=a+((p[i]-1)*(fact[n-i-1]))
	b=b+((q[i]-1)*(fact[n-i-1]))
	for j in range(i+1,n):
		if(p[j]>p[i]):
			p[j]=p[j]-1
		if(q[j]>q[i]):
			q[j]=q[j]-1
print(abs(a-b))

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    p = LI()
    q = LI()
    a = 0
    b = 0
    k = 1
    for pe in permutations(range(1,n+1)):
        if list(pe) == p:
            a = k
        if list(pe) == q:
            b = k
        if a&b:
            break
        k += 1
    print(abs(a-b))
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools

N = int(input())
p_i = tuple(map(int, input().split()))
q_i = tuple(map(int, input().split()))

N_lists = [i + 1 for i in range(N)]
order = []

for v in itertools.permutations(N_lists, N):
    order.append(v)

print(abs(order.index(p_i) - order.index(q_i)))

Submission status: Accepted

Solution code:
import sys
import math
N=int(input())
P=list(map(int,input().split()))
temp=[0]*N
cp=[i for i in range(1,N+1)]
Q=list(map(int,input().split()))
for i in range(N):
    temp[i]=cp.index(P[i])
    cp.remove(P[i])

rank=0
for i in range(N):
    rank+=temp[i]*math.factorial(N-i-1)
Pr=rank
cp=[i for i in range(1,N+1)]
for i in range(N):
    temp[i]=cp.index(Q[i])
    cp.remove(Q[i])
rank=0
for i in range(N):
    rank+=temp[i]*math.factorial(N-i-1)
Qr=rank
print(abs(Pr-Qr))

Submission status: Accepted

Solution code:
N=int(input())
pn=tuple(int(i) for i in input().split())
qn=tuple(int(i) for i in input().split())
l=[]
for i in range(1,N+1):
    l.append(i)
import itertools
ln=list(itertools.permutations(l))
print(abs(ln.index(pn)-ln.index(qn)))

Submission status: Accepted

Solution code:
from functools import reduce
n = int(input())
def r(n, m, l):
    if n == 1:
        return [m * 10 + l[0]]
    return reduce(lambda a, b: a + b, [r(n-1, m * 10 + l[i], l[:i] + l[i + 1:]) for i in range(0, n)])
d = r(n, 0, list(range(1, n+1)))
p = int(reduce(lambda a, b: a + b, input().split()))
q = int(reduce(lambda a, b: a + b, input().split()))
print(abs(d.index(q) - d.index(p)))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math

N = int(input())
P = input().split()
Q = input().split()
a = 1
b = 1
la = list(range(1,N+1))
lb = list(range(1,N+1))
#print(la)
#print(lb)
for i in range(N-1):
  a += (la.index(int(P[i]))-1)*math.factorial(N-1-i)
  la.remove(int(P[i]))
  b += (lb.index(int(Q[i]))-1)*math.factorial(N-1-i)
  lb.remove(int(Q[i]))
  #print(la)
  #print(lb)
#a = a - int(P[-1])+1
#b = b - int(Q[-1])+1
print(abs(b-a))

Submission status: Accepted

Solution code:
import itertools

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

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

a = sorted_num.index(p)
b = sorted_num.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()))


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

c = list(itertools.permutations(n))

count = 1
for i in c:
    if i == P:
        p = count
    if i == Q:
        q = count
    count += 1

print(abs(p-q))

Submission status: Accepted

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

used = [False]*N
pth = 0
for i in range(N):
    used[P[i] - 1] = True
    pth += ((P[i] -1) - used[:P[i]-1].count(True)) *math.factorial(N-i-1)

used = [False]*N
qth = 0
for i in range(N):
    used[Q[i] - 1] = True
    qth += ((Q[i] -1) - used[:Q[i]-1].count(True) ) *math.factorial(N-i-1)

print(abs(pth - qth + 1 -1))

Submission status: Accepted

Solution code:
import math
n = int(input())
l1 = list(range(1,n+1))
l2 = list(range(1,n+1))
n2 = n
p = list(map(int,input().split()))
q = list(map(int,input().split()))
ans_p = 1
ans_q = 1
# print(l1)
for i in range(n):
    ans_p += (math.factorial(n-1)) * l1.index(p[0])
    # print(p.index(i+1))
    # print(i)
    l1.remove(p[0])
    p.remove(p[0])
    n-=1
# print(ans_p)
for j in range(n2):
    ans_q += (math.factorial(n2-1)) * l2.index(q[0])
    # print((math.factorial(n2)) * l2.index(q[0]))
    # print(p.index(i+1))
    # print(i)
    l2.remove(q[0])
    q.remove(q[0])
    n2 -= 1

# print(ans_p)
# print(ans_q)
print(abs(ans_p-ans_q))

Submission status: Accepted

Solution code:
import math

def count_index(list, k):
    count = 0
    for i in range(k):
        if (list[i] < list[k]):
            count = count + 1
    return list[k]-count-1

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

a = (p[0]-1) * math.factorial(n)+1
b = (q[0]-1) * math.factorial(n)+1

for i in range(1,n):
    a = a + count_index(p, i) * math.factorial(n-i)
    b = b + count_index(q, i) * math.factorial(n-i)

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

Submission status: Accepted

Solution code:
n=int(input())
p_list = tuple(list(map(int,input().split())))
q_list = tuple(list(map(int,input().split())))

import itertools
count = 0
count_p = 0
count_q = 0

for i in itertools.permutations((range(1, n+1))):
    count += 1
    if i == p_list:
        count_p = count
    if i == q_list:
        count_q = count

print(abs(count_p - count_q))

Submission status: Accepted

Solution code:
import itertools

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

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

nnum = 1
for i in nlst:
    if i == p:
        break
    else:
        nnum += 1

qnum = 1
for i in nlst:
    if i == q:
        break
    else:
        qnum += 1

if nnum >= qnum:
    print(nnum - qnum)
else:
    print(qnum - nnum)

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = input().split()
for i in range(N):
    P[i] = int(P[i])
P = tuple(P)
Q = input().split()
for i in range(N):
    Q[i] = int(Q[i])
Q = tuple(Q)
counter = 1
count = 1
N_list = []
NN = [i + 1 for i in range(N)]
for j in itertools.permutations(NN,N):
    N_list.append(j)

k = 0
l = 0
i = 0
j = 0
while k == 0:
    if N_list[i] == P:
        break
    else:
        counter += 1
        i += 1

while l == 0:
    if N_list[j] == Q:
        break
    else:
        count += 1
        j += 1
a = counter
b = count
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

N=int(input())
P=(input().split())
Q=(input().split())
p=tuple(P)
q=tuple(Q)

seq=[]
for j in range(1,N+1):
  seq.append(str(j))
l=[]
for k in itertools.permutations(seq, N):
  l.append(k)

c1=0
c2=0
a=0
b=0
for m in range(len(l)):
  c1+=1
  c2+=1
  if p == l[m]:
    a=c1
  if q == l[m]:
    b=c2

print(abs(a-b))

Submission status: Accepted

Solution code:
N = int(input())
import numpy as np
P = np.array(list(map(int,input().split())))
Q = np.array(list(map(int,input().split())))
l = [0]*N
l[0]=1
for i in range(2,N+1):
  l[i-1]=l[i-2]*i

a = 0
b=0
for i in range(N):
  p=P[0]
  P=P[1::]
  q=Q[0]
  Q=Q[1::]
  P[P>p]-=1
  Q[Q>q]-=1
  a += l[N-2]*(p-1)+1
  b += l[N-2]*(q-1)+1
  N-=1
  
a-=N-1
b-=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()))

NumP = 0
NumQ = 0

for i in range(0,N):
    NumP += (P[i]-1) * math.factorial(N-1-i)
    NumQ += (Q[i]-1) * math.factorial(N-1-i)
    for j in range(i+1,N):
        if P[j] > P[i]:
            P[j] -= 1
        if Q[j] > Q[i]:
            Q[j] -= 1
NumP += 1
NumQ += 1

if NumP > NumQ:
    print(NumP-NumQ)
else:
    print(NumQ-NumP)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import math
import bisect
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))

pos_p = 1
pos_q = 1
cnt = n-1

for i in range(n):
    tmp_p = p[i:]
    tmp_p.sort()
    tmp_rank = bisect.bisect_left(tmp_p, p[i])
    pos_p += math.factorial(cnt) * tmp_rank

    tmp_q = q[i:]
    tmp_q.sort()
    tmp_rank = bisect.bisect_left(tmp_q, q[i])
    pos_q += math.factorial(cnt) * tmp_rank

    cnt -= 1

print(abs(pos_p-pos_q))

Submission status: Accepted

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

import math

lst = [_ for _  in range(1,n+1)]

i = 1
lst = [_ for _  in range(1,n+1)]
for _ in p:
    idx = lst.index(_)
    i += math.factorial(len(lst)) // len(lst) * idx
    lst.remove(_)

pans = i

i = 1
lst = [_ for _  in range(1,n+1)]
for _ in q:
    idx = lst.index(_)
    i += math.factorial(len(lst)) // len(lst) * idx
    lst.remove(_)

qans = i

ans = abs(pans - qans)
print(ans)