Problem:


Score : 300 points

Problem Statement

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

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

Notes

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

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

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

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

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

Sample Input 2

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

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0



Sample input:
3
1 3 2
3 1 2


Sample output:
3

Submission status: Accepted

Solution code:
import sys
import math
import bisect
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def I(): return int(sys.stdin.readline())


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


# A
def A():
    K, X = LI()
    if K * 500 >= X:
        print("Yes")
    else:
        print("No")
    return


# B
def B():
    n = I()
    s = S()
    cnt = 0
    for i in range(n - 2):
        if s[i] == "A":
            if s[i + 1] == "B" and s[i + 2] == "C":
                cnt += 1
    print(cnt)
    return


# C
def C():
    n = I()
    p = LI()
    q = LI()
    a_cnt = [1] * n
    b_cnt = [1] * n
    a = 0
    b = 0
    for i in range(1, n + 1):
        num = 1
        for j in range(1, n + 1 - i):
            num *= j
        a += sum(a_cnt[:p[i - 1]]) * num
        b += sum(b_cnt[:q[i - 1]]) * num
        a_cnt[p[i - 1] - 1] = 0
        b_cnt[q[i - 1] - 1] = 0
    print(abs(a - b))
    return


# D
def D():
    return


# E
def E():
    return


# F
def F():
    return


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

Submission status: Accepted

Solution code:
import math
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
def calc(P):
    data = list(range(0,len(P)))
    re = 0
    for i in range(len(P)):
        if data[P[i] - 1] > 0:
            re += data[P[i] -1]*math.factorial(len(P) - 1 -i)
        for j in range(P[i] - 1, len(P)):
            data[j] -= 1
    return re
a = calc(P)
b = calc(Q)
print(abs(a-b))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
from itertools import permutations

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

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

a = 0
b = 0
index = 0
for v in permutations(num_list,N):
    if v == P:
        a = index
    if v == Q:
        b = index

    index += 1

print(abs(a-b))

Submission status: Accepted

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

#print(p)
#print(q)
r = list(range(1,n+1))
E = list(itertools.permutations(r))
#print(r)
#print(e)
pi = 0
qi = 0
for i in range(0,len(E)):
    if p == list(E[i]):
        pi = i
        #print(pi)
    if q == list(E[i]):
        qi = i
        #print(qi)

print(abs(pi - qi))

Submission status: Accepted

Solution code:
import math
n=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
L=[]
R=[]
ans=0
p,q=0,0
cntp,cntq=0,0
for i in range(n):
  L.append(i+1)
  R.append(i+1)
  

for i in range(n):
    for j in L:
        if P[i] > j:
            cntp += 1
    for j in R:
        if Q[i] > j:
            cntq += 1
            
    p+=cntp*math.factorial(n-i-1)
    q+=cntq*math.factorial(n-i-1)
   
    L.remove(P[i])
    R.remove(Q[i])
    cntp,cntq=0,0
print(abs(p-q))

Submission status: Accepted

Solution code:
from itertools import permutations

n = int(input())
pi = list(map(int, input().split()))
qi = list(map(int, input().split()))

for i, p in enumerate(permutations(list(range(1,n+1)))):
    if "".join(map(str, pi)) == "".join(map(str, p)):
        a = i+1
    if "".join(map(str, qi)) == "".join(map(str, p)):
        b = i+1
print(abs(a-b))

Submission status: Accepted

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

L0 = list(range(1, N+1))
L = list(itertools.permutations(L0))
# print(L)
print(abs(L.index(tuple(P)) - L.index(tuple(Q))))

Submission status: Accepted

Solution code:
N = int(input())
nums1 = list(map(int, input().split()))
nums2 = list(map(int, input().split()))
r1 = 1
r2 = 1
def getOrder(nums):
    r = 1
    base = 1
    for i in range(N):
        base *= (i + 1)
    for idx in range(N):
        base //= (N - idx)
        s = {n: i for i, n in enumerate(sorted(nums[idx:]))}
        orders = [s[i] for i in nums[idx:]]
        r += orders[0] * base
    return r
a = (getOrder(nums1))
b = (getOrder(nums2))
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()))

ansp=1
ansq=1

for i in range(n):
    count=0
    for j in range(i+1,n):
        if p[i]>p[j]:
            count+=1
    ansp+=count*math.factorial(n-i-1)

for i in range(n):
    count=0
    for j in range(i+1,n):
        if q[i]>q[j]:
            count+=1
    ansq+=count*math.factorial(n-i-1)
print(abs(ansp-ansq))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from itertools import permutations
n=int(input())
z=[]
p=[i+1 for i in range(n)]
for i in permutations(p,n):
    z.append(list(i))
z.sort()
s=list(map(int,input().split()))
t=list(map(int,input().split()))
for i in range(len(z)):
    if z[i]==s:
        a=i
    if z[i]==t:
        b=i
print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations
N = int(input())
P = "".join(list(map(str,input().split())))
Q = "".join(list(map(str,input().split())))
ls = permutations(list(range(1,N+1)))
ans = []
for i in list(ls):
    ans.append("".join(list(map(str,i))))
ans = sorted(ans)
a,b = 0,0
for i in range(len(ans)):
    if ans[i] == P:
        a = i+1
    if ans[i] == Q:
        b = i+1
print(abs(int(a)-int(b)))

Submission status: Accepted

Solution code:
import itertools

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

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

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

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

p_i = comb.index(p)
q_i = comb.index(q)

print(abs(p_i-q_i))

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(map(list,list(itertools.permutations(list(i for i in range(1,N+1)),N))))
a = L.index(P)
b = L.index(Q)
print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations as p


def main():
    N = int(input())
    P = list(map(int, input().split(" ")))
    Q = list(map(int, input().split(" ")))
    l = []
    for i in range(1, N + 1):
        l.append(i)
    ints = []
    for k in p(l, N):
        ints.append(list(k))
    print(abs(ints.index(P) - ints.index(Q)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools
n=int(input())
a=tuple(input().split())
b=tuple(input().split())

a2=0
b2=0
seq=[]

for i in range(n):
    seq.append(str(i+1))

an=list(itertools.permutations(seq))

c=0
while a2==0 or b2==0:
    if a==an[c]:
        a2=c+1
    
    if b==an[c]:
        b2=c+1
    
    c+=1

print(abs(a2-b2))

Submission status: Accepted

Solution code:
if __name__ == '__main__':
  from itertools import permutations
  N = int(input())
  P = input()
  P = ''.join(P.split())
  Q = input()
  Q = ''.join(Q.split())
  
  base = ''
  for i in range(N):
    base += str(i+1)
  
  perm = sorted(''.join(chars) for chars in permutations(base))
  x = -1
  y = -1
  for idx, p in enumerate(perm):
    if P == p:
      x = idx
    if Q == p:
      y = idx
    if not (x == -1) and not (y == -1):
      break
  print(abs(x-y))

Submission status: Accepted

Solution code:
N=int(input())
P=list(map(str,input().split()))
Q=list(map(str,input().split()))
import itertools
S="".join(map(lambda x:str(x),range(1,N+1)))
A=list(itertools.permutations(S))
#print(A)
P_N = 0
Q_N = 0

QQ = ()
for q in Q:
  QQ += tuple(q)
PP = ()
for p in P:
  PP += tuple(p)
ind=1
for s in A:
  if QQ == s:
    Q_N = ind
  if PP == s:
    P_N = ind
  ind += 1
print(abs(P_N - Q_N))

Submission status: Accepted

Solution code:
import itertools
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
base=[]
for i in itertools.permutations(range(1,n+1)):
    base.append(list(i))
p_index=base.index(p)+1
q_index=base.index(q)+1
ans=abs(p_index-q_index)
print(ans)

Submission status: Accepted

Solution code:
import math
import itertools


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

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

    a = 0
    b = 0

    for i in range(len(permutations)):

        if permutations[i] == P:
            a = i

        if permutations[i] == Q:
            b = i
    print(abs(a-b))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools

n = int(input())
a = tuple([int(i) for i in input().split()])
b = tuple([int(i) for i in input().split()])
ai = 0
bi = 0
i = 1
val = [None] * n

for i in range(n):
    val[i] = i+1
for v in itertools.permutations(val, n):
    if v == a: ai = i-1
    if v == b: bi = i-1
    i += 1

print(abs(ai-bi))

Submission status: Accepted

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

def bikkuri(n):
    a=1
    for i in range(1,n+1):
        a*=i
    return a

ans=0
for i in range(n):
    pcnt=0
    qcnt=0
    for j in range(i+1,n):
        if p[i]>p[j]:
            pcnt+=1
        if q[i]>q[j]:
            qcnt+=1
    ans+=(pcnt-qcnt)*bikkuri(n-i-1)
print(abs(ans))

Submission status: Accepted

Solution code:
import itertools
import math
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
lista = [None]*n
for i in range(n):
    lista[i] = i+1
listb =[]
for i in itertools.permutations(lista):
    listb.append(i)
pp = listb.index(p)+1
qq = listb.index(q)+1
print(abs(pp-qq))

Submission status: Accepted

Solution code:
def rekkyo(n, s):
  if len(s) == n:
    rek.append(int(s))
    return
  
  for i in range(1, n+1):
    if not str(i) in s:
      rekkyo(n, s + str(i))
     
  return

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

rek = []
rekkyo(n, '')

rek.sort()
p_pos = rek.index(p)
q_pos = rek.index(q)

if p_pos < q_pos:
  ans = q_pos - p_pos
else:
  ans = p_pos - q_pos

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(input().split())
q = list(input().split())
p = ''.join(p)
q = ''.join(q)
n_list = [str(i) for i in range(1, n + 1)]
n_comp = list(itertools.permutations(n_list, n))
n_join = []

for i in n_comp:
    n_join.append(''.join(i))
n_join.sort()

a = 0
b = 0
for i in range(len(n_join)):
    if n_join[i] == p:
        a = i + 1
    if n_join[i] == q:
        b = i + 1
print(abs(a - b))

Submission status: Accepted

Solution code:
import math

N = int(input())
PN = list(map(int, input().split()))
QN = list(map(int, input().split()))

def listCount(_list):
    length = len(_list)

    lessList = []
    for i in range(length):
        lessCount = 0
        for j in range(i):
            if _list[i] > _list[j]:
                lessCount += 1
        lessList.append((_list[i] - 1) - lessCount)

    result = 0
    for i in range(length):
        result += (lessList[i]) * math.factorial(length-i-1)

    return result

PNCount = listCount(PN)
QNCount = listCount(QN)
print(abs(PNCount - QNCount))

Submission status: Accepted

Solution code:
import itertools

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

a = None
c = 0
for x in itertools.permutations(range(N), N):
    c += 1
    if x == P:
        if a is None:
            a = c
        else:
            print(abs(a - c))
            exit()
    if x == Q:
        if a is None:
            a = c
        else:
            print(abs(a - c))
            exit()

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))
p_count = 0
q_count = 0
count = 0
k = []
for i in range(N):
    k.append(i+1)
for i in itertools.permutations(k,N):
    count += 1
    if i == P:
        p_count = count
    if i == Q:
        q_count = count

sum = abs(p_count-q_count)
print(sum)

Submission status: Accepted

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

a = 0
b = 0
nums = list(range(N+1)[1:])
for i, p in enumerate(P):
  if i+1 == N:
    break
  a += math.factorial(N-1-i) * (nums.index(p)) + 1
  nums.pop(nums.index(p))

nums = list(range(N+1)[1:])
for i, q in enumerate(Q):
  if i+1 == N:
    break
  b += math.factorial(N-1-i) * (nums.index(q)) + 1
  nums.pop(nums.index(q))

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

def order(l):
    ans=0
    a=list(range(N))
    for i in range(N):
        ans+= a[l[i]-1]*math.factorial(N-1-i)
        for j in range(l[i],N):
            a[j]-=1
    return ans
p=order(P)
q=order(Q)
print(abs(p-q))

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

def reorder(que, v):
  for i in range(len(que)):
    if que[i] > v:
      que[i] -= 1
  return que

def factorial(n):
  if n > 1:
    return n * factorial(n-1)
  return 1

def get_order(que):
  n = 0
  while(que):
    q = que.popleft()
    n += ((q-1) * factorial(len(que)))
    que = reorder(que, q)
  return n

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

n = get_order(P)
m = get_order(Q)
print(abs(n-m))

Submission status: Accepted

Solution code:
import itertools

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

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

database = list(itertools.permutations(N_list))

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

Submission status: Accepted

Solution code:

#coding:utf-8

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

p = 0
q = 0
i = 0
for it in itertools.permutations(range(1, n + 1)):
    it = list(it)
    it = ''.join([str(num) for num in it])
    if it == a:
        p = i
    if it == b:
        q = i
    
    i += 1
print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = tuple([int(i) for i in input().split()][0:N])
Q = tuple([int(i) for i in input().split()][0:N])
l = list(itertools.permutations(range(1,N+1)))
print(abs(l.index(Q) - l.index(P)))

Submission status: Accepted

Solution code:
import itertools

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

if p_list == q_list:
	print(0)
else:
	a, b = 0, 0
	permutation = list(itertools.permutations(range(1,n+1)))
	for i, p in enumerate(permutation):
		pl = list(p)
		if pl == p_list:
			a = i
		elif pl == q_list:
			b = i
	print(abs(a-b))

Submission status: Accepted

Solution code:
def p_(val):
    ret = 1
    for i in range(2, val+1):
        ret *= i
    return ret


def func(n, val):
    l = [j for j in range(1, n+1)]
    idx = 0
    for i, val_i in enumerate(val[:-1]):
        idx += (l.index(val_i)) * p_(n - 1 - i)
        l.pop(l.index(val_i))
    return idx


n = int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
print(abs(func(n, p) - func(n, q)))

Submission status: Accepted

Solution code:
from sys import stdin
import math

N = int(stdin.readline().rstrip())
P = [int(x) for x in stdin.readline().rstrip().split()]
Q = [int(x) for x in stdin.readline().rstrip().split()]
rp = [int(x + 1) for x in range(N)]
rq = [int(x + 1) for x in range(N)]

index_p = 0
index_q = 0

for i in range(N):
    index_p += math.factorial(N - i - 1) * (rp.index(P[i]) - 1)
    index_q += math.factorial(N - i - 1) * (rq.index(Q[i]) - 1)
    rp.remove(P[i])
    rq.remove(Q[i])

print(abs(index_p - index_q))

Submission status: Accepted

Solution code:
import itertools
import copy
import math

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

Psorted = copy.copy(P)
Psorted.sort()
PQList = list(itertools.permutations(Psorted))

a = 0
b = 0
for i in range(math.factorial(N)):
    if PQList[i] == tuple(P):
        a = i + 1
    if PQList[i] == tuple(Q):
        b = i + 1
res = a - b
if res < 0:
    res *= -1

print(res)

Submission status: Accepted

Solution code:
import itertools

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

list = []
numList = []

for i in range(N + 1):
  if i == 0:
    continue
  numList.append(i)
  
for x in itertools.permutations(numList):
  list.append(x)

a = 0
b = 0

for index, t in enumerate(list):
  if t == P:
    a = index + 1
  
  if t == Q:
    b = index + 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()))
nn = [i+1 for i in range(n)]
mm = list(itertools.permutations(nn))
print(max((mm.index(q)) - (mm.index(p)) , (mm.index(p)) - mm.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=list(itertools.permutations(range(1,n+1)))
print(abs(l.index(p)-l.index(q)))

Submission status: Accepted

Solution code:
import math
n=int(input())
s=list(map(int,input().split()))
t=list(map(int,input().split()))
a=0
b=0
suuzi1=[i for i in range(1,n+1)]
suuzi2=[i for i in range(1,n+1)]
for i in range(n):
    a+=suuzi1.index(s[i])*math.factorial(n-i-1)
    suuzi1.remove(s[i])
for i in range(n):
    b+=suuzi2.index(t[i])*math.factorial(n-i-1)
    suuzi2.remove(t[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()))
factorial = [1,2,6,24,120,720,5040,40320] 

a = [i for i in range(1,n+1)]
cnt = 0
for i in range(n):
    if i == 0:
        cnt += (p[0]-1)*factorial[(n-i-1)-1]
        a.remove(p[0])
    else:
        if a.index(p[i]) == 0:
            if i == n-1:
                cnt += 1 
        else:
            cnt += a.index(p[i]) * factorial[(n-i-1)-1]
        a.remove(p[i])
a = [i for i in range(1,n+1)]
cnt_q = 0
for i in range(n):
    if i == 0:
        cnt_q += (q[0]-1)*factorial[(n-i-1)-1]
        a.remove(q[0])
    else:
        if a.index(q[i]) == 0:
            if i == n-1:
                cnt_q += 1 
        else:
            cnt_q += a.index(q[i]) * factorial[(n-i-1)-1]
        a.remove(q[i])
print(abs(cnt-cnt_q))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = input().replace(' ', '')
q = input().replace(' ', '')

for i, num in enumerate(itertools.permutations(range(1,n+1))):
    num = ''.join(map(str, list(num)))
    if num == p:
        break
for j, num in enumerate(itertools.permutations(range(1,n+1))):
    num = ''.join(map(str, list(num)))
    if num == q:
        break

print(abs(i-j))

Submission status: Accepted

Solution code:
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
if p==q:
  print(0)
  exit()
op=[i for i in range(1,n+1)]
oq=op[:]
r=[5040,720,120,24,6,2,1][8-n:]
a,b=1,1
for i in range(n-1):
  a+=op.index(p[i])*r[i]
  b+=oq.index(q[i])*r[i]
  op.remove(p[i])
  oq.remove(q[i])
print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations

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

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

Submission status: Accepted

Solution code:
import itertools
import math
n = int(input())
p  = list(map(int, input().split()))
q  = list(map(int, input().split()))
lst = []
for i in range(1, n+1):
    lst.append(i)
a =  list(itertools.permutations(lst))
p_c = a.index(tuple(p))
q_c = a.index(tuple(q))
print(int(math.fabs(q_c-p_c)))

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(" ")]
l = [x for x in range(1, N + 1)]
p = itertools.permutations(l, N)

P = tuple(P)
Q = tuple(Q)
p_index = 0
q_index = 0
for index, v in enumerate(p):
    if v == P:
        p_index = index
    if v == Q:
        q_index = index

print(abs(p_index - q_index))

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:
    ans = 0
else:
    PQ = [P] + [Q]
    PQ = sorted(PQ)

    li = list(range(N))
    li = list(map(lambda x: x + 1, li))

    i = 0
    j = 0
    a = []
    for v in itertools.permutations(li, N):
        j += 1
        if PQ[i] == v:
            a.append(j)
            if i == 1:
                break
            else:
                i += 1

    ans = a[1] - a[0]

print(ans)

Submission status: Accepted

Solution code:
N = int(input().strip())
#P = map(int, input().strip().split())
#Q = map(int, input().strip().split())
P = int(input().strip().replace(" ", ""))
Q = int(input().strip().replace(" ", ""))

import itertools

seq = [str(i) for i in range(1,N+1)]
alllist = sorted([int("".join(l)) for l in list(itertools.permutations(seq))])
print(abs(alllist.index(P)-alllist.index(Q)))

Submission status: Accepted

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N = int(input())
kakuran = list(itertools.permutations(range(1,N+1)))
# print(kakuran)
PP = tuple(inpl())
QQ = tuple(inpl())

a = kakuran.index(PP)
b = kakuran.index(QQ)

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

seq = range(1,N+1)
Nlist=list(itertools.permutations(seq))
for index,lists in enumerate(Nlist):
    if lists == P:
        a = index
        break

for index,lists in enumerate(Nlist):
    if lists == Q:
        b = index
        break

print(abs(a-b))

Submission status: Accepted

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

a = 0
b = 0
c = 1
for v in itertools.permutations(ls, n):
    if list(v) == p:
        a = c
    if list(v) == q:
        b = c
    c += 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()))

def f(li,a):
    li2=[]
    for j in range(len(li)):
        for i in range(len(li[j])+1):
            li2.append(li[j][i:]+[a]+li[j][:i])
    return li2


li=[[1]]

for i in range(2,n+1):
    li=f(li,i)
    
li.sort()


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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools

N = int(input()) 
P = input().split()
Q = input().split()

P = tuple(map(int,P))
Q = tuple(map(int,Q))

list_N = list(range(N))
list_N.append(N)
list_N.remove(0)
list_all = []

for i in itertools.permutations(list_N): 
    list_all.append(i)

a = (list_all.index(P)) + 1
b = (list_all.index(Q)) + 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()))
a=0
b=0
x=[i+1 for i in range(n)]
y=[i+1 for i in range(n)]

for i in range(n-1):
    a+=x.index(p[i])*math.factorial(n-1-i)
    b+=y.index(q[i])*math.factorial(n-1-i)
    x.remove(p[i])
    y.remove(q[i])


print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
n = input()
p = "".join(input().split())
q = "".join(input().split())
availables = ["".join(t) for t in list(itertools.permutations([str(i+1) for i in range(int(n))]))]
idx_p = availables.index(p)
idx_q = availables.index(q)
print(abs(idx_p-idx_q))

Submission status: Accepted

Solution code:
import itertools


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

    a = 0
    for i, p_per in enumerate(sorted(itertools.permutations(range(1, n+1))), start=1):
        if list(p_per) == p:
            a = i

    b = 0
    for j, q_per in enumerate(sorted(itertools.permutations(range(1, n+1))), start=1):
        if list(q_per) == q:
            b = j

    print(abs(a - b))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from math import factorial as ft

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

num = [1 for i in range(1,N+1)]
t1 = 0
for a in range(len(p)):
    t1 += ft(N-a-1)*num[:p[a]].count(1)
    num[p[a]-1] = 0
    # print(N-a-1, t1,num)
# print(t1)

num = [1 for i in range(1,N+1)]
t2 = 0
for a in range(len(q)):
    t2 += ft(N-a-1)*num[:q[a]].count(1)
    num[q[a]-1] = 0
    # print(N-a-1, t2,num)
# print(t2)
print(abs(t1-t2))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import math
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
a=0
b=0
maxlist=[]
for i in range(N):
    maxlist.append(P[i])
    maxlist.sort()
    temp=maxlist.index(P[i])-1
    a=a+math.factorial(N-1-i)*(P[i]-1-temp)
maxlist=[]
for i in range(N):
    maxlist.append(Q[i])
    maxlist.sort()
    temp=maxlist.index(Q[i])-1
    b=b+math.factorial(N-1-i)*(Q[i]-1-temp)
print(max(a-b,b-a))

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import itertools
N = int(input())
num = [i for i in range(1,N+1)]
num_list = list(itertools.permutations(num))
ser_A = tuple(map(int,input().split()))
ser_B = tuple(map(int,input().split()))
A = 0
B = 0
for i in range(len(num_list)):
	if(num_list[i] == ser_A ):
		A = i+1
	if(num_list[i] == ser_B ):
		B = i+1
print(abs(A-B))

Submission status: Accepted

Solution code:
from math import factorial

def lexicographic_index(p):
    result = 0
    for j in range(len(p)):
        k = sum(1 for i in p[j + 1:] if i < p[j])
        result += k * factorial(len(p) - j - 1)
    return result

n = int(input())
p1 = "".join(input().split(" "))
p2 = "".join(input().split(" "))

print(abs(lexicographic_index(p1)- lexicographic_index(p2)))

Submission status: Accepted

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

p=set()
q=set()
r=[1]*N
r[0]=0
for j in range(N-2):
  i=j+1
  r[i+1]=r[i]*(i+1)
pnum=0
qnum=0
for i in range(N):
  k=0
  for j in range(P[i]):
    if {j+1}<=p:
      k=k
    else:
      k+=1
  pnum+=r[N-1-i]*(k-1)
  p.add(P[i])
  
  k=0
  for j in range(Q[i]):
    if {j+1}<=q:
      k=k
    else:
      k+=1
  qnum+=r[N-1-i]*(k-1)
  q.add(Q[i])
  
print(abs(pnum-qnum))

Submission status: Accepted

Solution code:
import itertools
_n = int(input())
n = range(1, _n + 1)
p = "-".join(list(map(str, input().split())))
q = "-".join(list(map(str, input().split())))
a = 0
b = 0
for i, x in enumerate(itertools.permutations(n)):
    _x = "-".join(list(map(str, x)))
    if p == _x:
        a = i + 1
    if q == _x:
        b = i + 1
    if a * b != 0:
        break
print(abs(a - b))

Submission status: Accepted

Solution code:
import sys, math
from math import factorial
def input():
    return sys.stdin.readline()[:-1]
from itertools import permutations, combinations
from collections import defaultdict, Counter
from bisect import bisect_left

sys.setrecursionlimit(10**7)
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))


orderP = 1
chk = []
for i, p in enumerate(P):
    chk_tmp = [1 if val < p else 0 for val in chk]
    cnt = sum(chk_tmp)
    orderP += (p - 1 - cnt) * factorial(N-(i+1))
    chk.append(p)    
    
orderQ = 1
chk = []
for i, q in enumerate(Q):
    chk_tmp = [1 if val < q else 0 for val in chk]
    cnt = sum(chk_tmp)
    orderQ += (q - 1 - cnt) * factorial(N-(i+1))
    chk.append(q)    

print(abs(orderP-orderQ))

Submission status: Accepted

Solution code:
import math

def counter(l, n):
    num = list(range(1,n+1))
    index = 0
    order = 0
    for i in range(n):
        index = num.index(l[i])
        order += math.factorial(n-i-1)*index
        del num[index]
    
    return order


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

print(abs(counter(ps,n)-counter(qs,n)))

Submission status: Accepted

Solution code:
from itertools import permutations

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

cnt_p = 0
cnt_q = 0

for i, v in enumerate(permutations(range(1, N + 1), N)):
    if v == P:
        cnt_p = i
    if v == Q:
        cnt_q = i
        
print(abs(cnt_p - cnt_q))