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())
a = tuple(input().split())
b = tuple(input().split())

num = list(str(i) for i in range(1,n+1))
iters = list(itertools.permutations(num))

for i in range(len(iters)):
  if a == iters[i]:
    A = i
  elif b == iters[i]:
    B = i

if a == b:
  print(0)
else:
  print(abs(A-B))

Submission status: Accepted

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

Pj = 0

for i in range(N-1):
  k = i + 1  
  Pj = Pj + sum(1 for x in P[k:] if P[i] > x) * math.factorial(N-1-i)

Pj += 1

Qj = 0

for i in range(N-1):
  k = i + 1  
  Qj = Qj + sum(1 for x in Q[k:] if Q[i] > x) * math.factorial(N-1-i)

Qj += 1

print(abs(Pj - Qj))

Submission status: Accepted

Solution code:
import math
import random
from operator import itemgetter
import re
import sys
from itertools import accumulate
from collections import defaultdict
from collections import deque
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import functools
N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
ans = 0
for i in range(N):
    ans += (Q[i]-P[i])*math.factorial(N-1-i)
    for j in range(N-1-i):
        if Q[i+j+1] >Q[i]:
             Q[i+j+1] -= 1
        if P[i+j+1] >P[i]:
             P[i+j+1] -= 1
print(abs(ans))

Submission status: Accepted

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

import itertools
tmp = [i for i in range(1,N+1)]
#print(tmp)
tmp2 = itertools.permutations(tmp)
a,b = 0,0
for n,j in enumerate(tmp2):
  #print(n,j)
  if list(j)==P:
    a = n+1
    #print(a)
  if list(j)==Q:
    b = n+1
    #print(b)
res=abs(a-b)

print(res)

Submission status: Accepted

Solution code:
# coding: utf-8

import math

N = int(input())

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

n = list(range(1, N + 1))
a = 1
for i in range(len(P) - 1):
	a += math.factorial(N - i - 1) * (n.index(P[i]))
	n.remove(P[i])

n = list(range(1, N + 1))
b = 1
for i in range(len(Q) - 1):
	b += math.factorial(N - i - 1) * (n.index(Q[i]))
	n.remove(Q[i])

print(abs(a - b))

Submission status: Accepted

Solution code:
import math
from bisect import bisect_left
N=int(input())
P=[int(i) for i in input().split()]
Q=[int(i) for i in input().split()]
a=1
b=1
for i,n in enumerate([m for m in range(1,N+1)]):
    if min(P[i:])<P[i]:
        a+=bisect_left(sorted(P[i:]),P[i])*math.factorial(N-i-1)
    if min(Q[i:])<Q[i]:
        b+=bisect_left(sorted(Q[i:]),Q[i])*math.factorial(N-i-1)
print(abs(a-b))

Submission status: Accepted

Solution code:
def kaijo(m):
    kotae=1
    for i in range(1,m+1):
        kotae*=i
    return kotae

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

for i in range(n):
    p[i]-=1
    q[i]-=1

pnum=0
qnum=0

pki=[[]for i in range(n)]
qki=[[]for i in range(n)]

for i in range(1,n):
    for j in range(i):
        pki[i].append(p[j])
        qki[i].append(q[j])

for i in range(n):
    kai=n-i-1
    count=0
    for j in range(p[i]):
        if(not j in pki[i]):
            count+=1
    pnum+=count*kaijo(kai)

    count=0
    for j in range(q[i]):
        if(not j in qki[i]):
            count+=1
    qnum+=count*kaijo(kai)

ans=pnum-qnum
ans=max(ans,-1*ans)

print(ans)

Submission status: Accepted

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

import itertools

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

a = list(range(1,n+1,1))
count = 1

res1 = 0
res2 = 0

temp = []

for i in itertools.permutations(a):
    for j in range(n):
        temp.append(i[j])
    if temp == p and (res1 == 0):
        res1 = count
    if temp == q and (res2 == 0):
        res2 = count
    count += 1
    temp = []

print(abs(res1-res2))

Submission status: Accepted

Solution code:
#!python3

def iim():
    return map(int, input().rstrip().split())

from math import factorial
def calc(a):
    N = len(a)
    aa = []
    bk = [factorial(i) for i in range(N-1, 0, -1)]

    bl = [0] * N
    for i in range(N-1, 0, -1):
        x = a[i]
        for j in range(i):
            if a[j] > x:
                bl[j] += 1

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

    return n

def resolve():
    N = int(input())
    P = list(iim())
    Q = list(iim())

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

if __name__ == "__main__":
    resolve()

Submission status: Accepted

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

import itertools

s = []

for j in range(N):
    s.append(j + 1)

n_P = 0
n_Q = 0

list_seed = list(itertools.permutations(s, N))
list_seed = [list(list_seed[i]) for i in range(len(list_seed))]

for i in range(len(list_seed)):
    if list_seed[i] == P:
        n_P = i + 1
    if list_seed[i] == Q:
        n_Q = i + 1

print(abs(n_P - n_Q))

Submission status: Accepted

Solution code:
import itertools
import math

n = int(input())
p = list(map(str,input().split()))
q = list(map(str,input().split()))
lst = []
for i in range(n):
    lst.append(str(i+1))
lst_perm = list(itertools.permutations(lst))
a=0
b=0
for i in range(math.factorial(n)):
    if ("".join(p))==("".join(q)):
        if ("".join(p))==("".join(lst_perm[i])):
            a=i
            b=i
    else:
        if ("".join(p))==("".join(lst_perm[i])):
            a = i
        elif ("".join(q))==("".join(lst_perm[i])):
            b = i
print(abs(a-b))

Submission status: Accepted

Solution code:
import sys
import itertools

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

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

ip = a.index(P)
iq = a.index(Q)

if ip-iq >= 0:
  print(ip-iq)
else:
  print(iq-ip)

Submission status: Accepted

Solution code:
A = input()
a = int(A)
B = input()
C = input()
res1 = tuple()
res2 = tuple()
from itertools import permutations 
l = list(permutations(range(1, a+1))) 
res1 = tuple(map(int, B.split(' ')))
res2 = tuple(map(int, C.split(' ')))
d = l.index(res1)
e = l.index(res2)
print(abs(d-e))

Submission status: Accepted

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

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

for i,e in enumerate(tank):
    if p == e:
        a = i
    if q == e:
        b = i
    #print(e)3
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

seq = itertools.permutations(range(1,N+1))
listseq = list(seq)
tupleA = tuple(A)
tupleB = tuple(B)

indexA = listseq.index(tupleA) + 1
indexB = listseq.index(tupleB) + 1

ans = abs(indexA - indexB)

print(ans)

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)
ll = list(itertools.permutations(l))

PP = ll.index(P)
QQ = ll.index(Q)

print(abs(PP - QQ))

Submission status: Accepted

Solution code:
import math

def CountOrder(n, a):
    used = []
    order = 0
    for i in range(len(a)):
        nn = a[i] - 1
        for u in used:
            if u < a[i]:
                nn -= 1
        used.append(a[i])

        order += nn * math.factorial(n - 1 - i)

    return order + 1
        
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

print(abs(CountOrder(n, a) - CountOrder(n, b)))

Submission status: Accepted

Solution code:
import itertools

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

l = list(range(1, N+1))
p = [list(v) for v in itertools.permutations(l, len(l))]

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

l=list(range(1,n+1))
ll=list(itertools.permutations(l,n))
pp=ll.index(p)
qq=ll.index(q)
a=pp-qq
if a<0:
  a=a*(-1)
print(str(a))

Submission status: Accepted

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

import math

Listp = []
for i in range(1,N):
    countp = 0
    for j in range(0,i):
        if P[j] <= P[i]:
            countp = countp + 1
        else:
            countp = countp
    Listp.append(countp)

Listq = []
for i in range(1,N):
    countq = 0
    for j in range(0,i):
        if Q[j] <= Q[i]:
            countq = countq + 1
    Listq.append(countq)


ansp = (P[0]-1)*math.factorial(N-1)
for i in range(1,N):
    ansp = ansp + (P[i]-Listp[i-1]-1)*math.factorial(N-i-1)
    
ansq = (Q[0]-1)*math.factorial(N-1)
for i in range(1,N):
    ansq = ansq + (Q[i]-Listq[i-1]-1)*math.factorial(N-i-1)
    
print(abs(ansp-ansq))

Submission status: Accepted

Solution code:
import math


def value(x_list, kaijo):

    num_list = list(range(len(x_list)+1))

    result = 1
    count = len(x_list)
    for x in x_list:
        kaijo /= count
        count -= 1
        target_value = num_list[x] - 1
        result += target_value * kaijo

        new_list = [0]*(len(x_list)+1)

        for i, num in enumerate(num_list):
            if num > target_value:
                new_list[i] = num-1
            else:
                new_list[i] = num

        num_list = new_list

    return int(result)


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

kaijo = math.factorial(N)

p_value = value(p_list, kaijo)
q_value = value(q_list, kaijo)
print(abs(p_value-q_value))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p_list = list(map(int, input().split()))
q_list = list(map(int, input().split()))
p_list = tuple(p_list)
q_list = tuple(q_list)
n_list = list(range(1, n+1))

a_list = list(itertools.permutations(n_list))
a = a_list.index(p_list)
b = a_list.index(q_list)

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=1
b=1

for i in range(n-1):
  c=0
  d=0
  for j in range(i+1,n):
    if p[i]>p[j]:
      c+=1
    if q[i]>q[j]:
      d+=1
  a+=c*math.factorial(n-i-1)
  b+=d*math.factorial(n-i-1)
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P_ar = list(map(int,input().split()))
Q_ar = list(map(int,input().split()))

List = list(map(list,list(itertools.permutations(range(N)))))

for i in range(N):
  P_ar[i]-=1
  Q_ar[i]-=1

a=-1
b=-1

for i in range(len(List)):
  if List[i]==P_ar:
    a=i
    break

for i in range(len(List)):
  if List[i]==Q_ar:
    b=i
    break

print(abs(a-b))

Submission status: Accepted

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

import math
import itertools
import numpy as np

s = [x for x in range(N + 1)][1:N+1]
strs = [str(s) for s in s]

i = 1
for v in itertools.permutations(strs):
    i = i + 1
    V = [int(v) for v in v]
    if V == P:
        a = i
    if V == Q:
        b = i
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 = [9] * N
B = [9] * N
Pcount = 0
Qcount = 0
Pnum = 1
Qnum = 1
Ans = 0

for i in range(N-1):
  for j in range(N):
    if P[i] > A[j]:
      Pcount = Pcount + 1
  
  for k in range(N):
    if Q[i] > B[k]:
      Qcount = Qcount + 1
    
  Pnum = Pnum + math.factorial(N - i - 1) * (P[i] - 1 - Pcount)
  Qnum = Qnum + math.factorial(N - i - 1) * (Q[i] - 1 - Qcount)
  
  A[i] = P[i]
  B[i] = Q[i]
  Pcount = 0
  Qcount = 0


Ans = abs(Pnum - Qnum)
#print(Pnum)
#print(Qnum)
print(Ans)

Submission status: Accepted

Solution code:
import numpy as np
import math

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

def _get_order(N, v, i):
  order=np.argsort(v[i:])
  return list(order).index(0) * math.factorial(len(order)-1)

def get_order(N, v):
  each_order=list(map(lambda i: _get_order(N, v, i), range(N)))
  return each_order
a = sum(get_order(N, P))
b = sum(get_order(N, Q))
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

def main():
    N = int(input())
    
    P = list(map(int, input().split()))
    Q = list(map(int, input().split()))
    
    combi = list(itertools.permutations(range(1, N+1)))
    
    pi = 0
    qi = 0
    for i in range(len(combi)):
        if list(combi[i]) == P:
            pi = i + 1
        if list(combi[i]) == Q:
            qi = i + 1
            
            
    print(abs(qi - pi))
    
main()

Submission status: Accepted

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

#def factor(x):
  #y=1
  #if x==0 or x==1:
    #return 1
  #else:
    #for i in range(1,x+1):
      #y*=i
    #return y
#jp=0
#jq=0
#for i in range(n):
  #jp+=(p[i]-1)*factor(n-i-1)
  #jq+=(q[i-1])*factor(n-i-1)
#print(jp,jq)
per=list(itertools.permutations(l))

for i in range(len(per)):
  #print(per[i],p)
  if per[i]==p:
    a=i
  if per[i]==q:
    b=i
print(abs(a-b))

Submission status: Accepted

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

def ans(l, con):
  if con == n - 1:
    return 0
  k = bisect.bisect_right(sorted(l[con:]),l[con])
  return k*math.factorial(n - 1 - con) + ans(l, con + 1)
print(abs(ans(p, 0)-ans(q,0)))

Submission status: Accepted

Solution code:
import collections as c
ip = lambda : map(int, input().split())
# ##############
N = int(input())
p = list(ip())
q = list(ip())

d = {0:1}
for i in range(1,N):
    d[i] = d[i-1]*i
# print(d)
ansp = 0
ansq = 0
lp = list(range(1,N+1))
lq = list(range(1,N+1))
for i in range(N-1):
    ansp += d[N-1-i]*(lp.index(p[i]))
    ansq += d[N-1-i]*(lq.index(q[i]))
    lp.pop(lp.index(p[i]))
    lq.pop(lq.index(q[i]))
    # print(ansp,ansq)
print(abs(ansp-ansq))

Submission status: Accepted

Solution code:
import itertools

N=int(input())
P=list((map(int,input().split())))
Q=list((map(int,input().split())))
cnt=1
for u in itertools.permutations(range(1,N+1)):
    for i in range(N):
        if u[i]==P[i]:
            continue
        else:
            break
    else:
        a=cnt
    for i in range(N):
        if u[i]==Q[i]:
            continue
        else:
            break
    else:
        b=cnt
    cnt+=1
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

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

print(abs(a-b))

Submission status: Accepted

Solution code:
n = int(input())

fact = [1]
for i in range(1, n):
  fact.append(fact[-1] * i)
  
check = [True] * (n+1)
check[0] = False

a = 1
for i, p in enumerate(map(int, input().split())):
  check[p] = False
  a += sum(check[:p]) * fact[n-i-1]
  
check = [True] * (n+1)
check[0] = False

b = 1
for i, p in enumerate(map(int, input().split())):
  check[p] = False
  b += sum(check[:p]) * fact[n-i-1]
  
print(abs(a-b))

Submission status: Accepted

Solution code:
import  itertools

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

for i, aaa in enumerate(itertools.permutations(range(1,N+1),N)):
    if P == list(aaa):
        num_P = i + 1

    if Q == list(aaa):
        num_Q = i + 1

print(abs(num_P-num_Q))

Submission status: Accepted

Solution code:
import math

def n_check(N,P):
  N_list = list(range(1,N+1))
  n = 0
  for i in P:
    n += (N_list.index(i))*(math.factorial(len(N_list)-1))
    N_list.remove(i)
  return n

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

p_n = n_check(N,P) + 1
q_n = n_check(N,Q) + 1

print(abs(p_n - q_n))

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()])
x=list(itertools.permutations(range(1,n+1)))
nc=len(x)

for i in range(nc):
  if x[i]==p:
    pn=i
    
for j in range(nc):
  if x[j]==q:
    qn=j


print(abs(pn-qn))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = int(input().replace(' ', ''))
Q = int(input().replace(' ', ''))
s = [i for i in range(1, N + 1)]
l = list(itertools.permutations(s))
j = []
for i in range(len(l)):
  t = map(str,l[i])
  j.append(int(''.join(t)))

nl = sorted(j) 
a = 0
b = 0

for i in range(len(nl)):
  if nl[i] == P:
    a = i + 1
  if nl[i] == Q:
    b = i + 1
    
print(abs(a -b))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
permute = list(map(list,list(itertools.permutations(range(1,n+1)))))


index_a = permute.index(a)
index_b = permute.index(b)
print(abs(index_a-index_b))

Submission status: Accepted

Solution code:
def heapPermutation(a, size, n,all_perms): 
	if (size == 1): 
		all_perms.append(a[:])
		return

	for i in range(size): 
		heapPermutation(a,size-1,n,all_perms)
		if size&1: 
			a[0], a[size-1] = a[size-1],a[0] 
		else: 
			a[i], a[size-1] = a[size-1],a[i] 
		

def main():
    n = int(input())
    p = list(map(int,input().split()))
    q = list(map(int,input().split()))
    arr = [i for i in range(1,n+1)]
    all_perms = []
    heapPermutation(arr,n,n,all_perms)
    all_perms.sort()
    a = -1
    b = -1
    for i in range(len(all_perms)):
        if all_perms[i] == p:
            a = i
        elif all_perms[i] == q:
            b = i

    if a == -1 or b == -1:
        print(0)
        return

    print(abs(a-b))


main()

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()]
a, b = 0, 0
P_l = [0] * N
Q_l = [0] * N
for i in range(N-1):
  P_l[P[i]-1] = 1
  a += (P[i] - 1 - sum(P_l[:P[i]-1])) * math.factorial(N-i-1)
  Q_l[Q[i]-1] = 1
  b += (Q[i] - 1 - sum(Q_l[:Q[i]-1])) * math.factorial(N-i-1)
print(abs(a-b))

Submission status: Accepted

Solution code:
from math import factorial

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

def f(X):
    c = 0
    a = [i+1 for i in range(n)]
    for i in range(n):
        a.sort()
        # print(X, a, c)
        if X[i]!=min(a):
            c += factorial(n-i-1)*(a.index(X[i]))
        del a[a.index(X[i])]
    return c+1

print(abs(f(P)-f(Q)))

Submission status: Accepted

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

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

L = list(itertools.permutations(M))

cnt = 0
pc = 0
qc = 0
for i in range(len(L)):
    cnt+=1
    K = list(L[i])
    if K==P:
        pc = cnt
    if K==Q:
        qc = cnt

print(abs(pc-qc))

Submission status: Accepted

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


def order(X):
    lst_n = list(range(1, N + 1))
    res = 0
    for i in range(N - 1):
        j = 0
        while True:
            if X[i] == lst_n[j]:
                res = (res + j) * (N - i - 1)
                lst_n = lst_n[:j] + lst_n[j + 1:]
                break
            j += 1
    return res + 1


print(abs(order(P) - order(Q)))

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()

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

    ls = [0] * 9
    ls[0] = 1
    for i in range(N):
        ls[i+1] = ls[i] * (i+1)

    p_sum = 0
    q_sum = 0
    p_ls = [1,2,3,4,5,6,7,8]
    q_ls = [1,2,3,4,5,6,7,8]
    for j in range(N):
        p_sum += p_ls.index(P[j]) * ls[N-j-1]
        p_ls.remove(P[j])
        q_sum += q_ls.index(Q[j]) * ls[N-j-1]
        q_ls.remove(Q[j])
    
    print(abs(p_sum - q_sum))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
n_list = [i for i in range(1,N+1)]
n_perm = sorted(list(itertools.permutations(n_list, N)))
a = 0
b = 0

for i in range(len(n_perm)):
    if list(n_perm[i]) == P:
        a = i
        break

for k in range(len(n_perm)):
    if list(n_perm[k]) == Q:
        b = k
        break
        
print(abs(a-b))

Submission status: Accepted

Solution code:
import math
import itertools

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
new_p = sorted(p)
new_q = sorted(q)
check = 0
roop = math.factorial(n)

list_p = []
list_q = []
for i in itertools.permutations(new_p):
    list_p.append(i)
for i in itertools.permutations(new_q):
    list_q.append(i)

check = 0
for i in range(roop):
    if list_p[i] == tuple(p):
        a = i
        check += 1
    if list_q[i] == tuple(q):
        b = i
        check += 1
    if check == 2:
        break

print(abs(a-b))

Submission status: Accepted

Solution code:
import math
from itertools import permutations

#print(math.factorial(5))
bi = 0
ci = 0

a = int(input())
b = list(input().split())
c = list(input().split())

bstr = ''.join(b)
cstr = ''.join(c)

blist = sorted([''.join(p) for p in permutations(b)])
clist = sorted([''.join(p) for p in permutations(c)])

for i in range(math.factorial(a)):
	if bstr == blist[i]:
		bi = i
	if cstr == clist[i]:
		ci = i
print(abs(bi - ci))
#print(blist)
#print(clist)

Submission status: Accepted

Solution code:
import itertools

N = int(input())
PER = []
for i in range(N):
    PER.append(i+1)

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

for x in itertools.permutations(PER):
     
    flag_a = 0
    flag_b = 0
 
    for i in range(N):
        if x[i] == P[i]:
            flag_a += 1   
        if x[i] == Q[i]:
            flag_b += 1
    if flag_b == N:
        b = tmp
    if flag_a == N:
        a = tmp
    tmp += 1

ans = a - b
if ans < 0:
    ans = - ans

print(ans)

Submission status: Accepted

Solution code:
import bisect
from math import factorial


n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
p_c = [i for i in range(1, n+1)]
q_c = [i for i in range(1, n+1)]
ans_p = 1
ans_q = 1
for i in range(n-1):
    p_c.pop(p_c.index(p[i]))
    q_c.pop(q_c.index(q[i]))
    ans_p += (bisect.bisect_left(p_c, p[i])) * factorial(n - i - 1)
    ans_q += (bisect.bisect_left(q_c, q[i])) * factorial(n - i - 1)
print(abs(ans_p - ans_q))

Submission status: Accepted

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

P1=P
P2=[0]*n
for i in range(n):
    P1=[p-1 if p>=P1[i] else p for p in P1]
    P2[i]=P1[i]
A=0
for j in range(n):
    A+=math.factorial(n-j-1)*P2[j]
    
Q1=Q
Q2=[0]*n
for i in range(n):
    Q1=[q-1 if q>=Q1[i] else q for q in Q1]
    Q2[i]=Q1[i]
B=0
for j in range(n):
    B+=math.factorial(n-j-1)*Q2[j]

print(abs(A-B))

Submission status: Accepted

Solution code:
# AtCoder Beginner Contest 150 : C (2020/01/10)
import itertools
N = int(input())
in_p = input().split()
in_q = input().split()
P = [0 for i in range(N)]
Q = [0 for i in range(N)]
for i in range(N):
    P[i] = int(in_p[i])
    Q[i] = int(in_q[i])
R = list(itertools.permutations(sorted(P)))
idx_P = 0
idx_Q = 0
for i in range(len(R)):
    if list(R[i]) == P:
        idx_P = i+1
    if list(R[i]) == Q:
        idx_Q = i+1
    if idx_P != 0 and idx_Q != 0:
        break
print(abs(idx_P-idx_Q))

Submission status: Accepted

Solution code:
import itertools

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

x = itertools.permutations(list(range(1, n+1)), n)
pnum = 0
qnum = 0
for index, xx in enumerate(x):
  if(list(xx) == p):
    pnum = index
  if(list(xx) == q):
    qnum = index
    
print(abs(pnum - qnum))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import math
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
ans = [0,0]
for pq in range(2):
    l = q if pq % 2 else p
    #print(l)
    for i in range(n-1):
        # p[i:]の中でp[i]はしたから何番目か
        k = sorted(l[i:]).index(l[i])
        ans[pq] += k*math.factorial(n-i-1)
print(abs(ans[0]-ans[1]))

Submission status: Accepted

Solution code:
from math import factorial


def solve(n,lst):
    nums = list(range(1,n+1))
    counter = 0
    for i in range(n):
        counter += (nums.index(lst[i])) * factorial(n-i-1)
        nums.pop(nums.index(lst[i]))
    return counter + 1




def main():
    n = int(input())
    lst1 = list(map(int,input().split()))
    lst2 = list(map(int,input().split()))
    lst1_ans = solve(n,lst1)
    lst2_ans = solve(n,lst2)
    answer = abs(lst1_ans - lst2_ans)
    print(answer)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from math import factorial
from itertools import permutations
n=int(input())
a=[]
ansp="a"
ansq="a"
p=[int(x) for x in input().split()]
q=[int(x) for x in input().split()]
for v in permutations(p, n):
    a.append(list(v))
a.sort()
for i in range(len(a)):
    if a[i]==p:
        ansp=i
    if a[i]==q:
        ansq=i
    if ansq!="a" and ansp!="a":
        break
print(max(ansp,ansq)-min(ansp,ansq))

Submission status: Accepted

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

p = input()
q = input()
p = p.split(" ")
q = q.split(" ")
p, q = tuple(map(int, p)), tuple(map(int, q))
print(abs(l.index(p) - l.index(q)))

Submission status: Accepted

Solution code:
#coding:utf-8
import sys
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something : print(*something) if DEBUG else 0
DEBUG = False
def main(given = sys.stdin.readline):
    input = lambda : given().rstrip()
    LMIIS = lambda : list(map(int,input().split()))
    II = lambda : int(input())
    XLMIIS = lambda x : [LMIIS() for _ in range(x)]

    N = II()
    P = input().replace(' ','')
    Q = input().replace(' ','')

    kouho = set(range(1,N+1))
    def kaijo(n):
        ans = 1
        for i in range(1,n+1):
            ans *= i
        return ans
    numbers = [0] * kaijo(N)
    # print(len(numbers))
    from copy import copy
    def mkp(kouho,i,p):
        if i == N-1:
            numbers.append(p+kouho[0])
            return

        for j in range(len(kouho)):
            kouho2 = copy(kouho)
            kouho2.remove(kouho[j])
            mkp(kouho2,i+1,p+kouho[j])
    mkp(list(map(str,range(1,N+1))),0,'')
    numbers = numbers[kaijo(N):]


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



   




if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math
N=int(input())
lst=[int(s) for s in input().split()]
lst2=[int(s) for s in input().split()]
def ind(ls):
  cha=[i+1 for i in range(N)]
  ans=1
  for i in range(N):
    x=cha.index(ls[i])
  #  print(x)
    ans+=(x)*math.factorial(N-1-i)
   # print(ans)
    cha.remove(ls[i])
  return ans
a=ind(lst)
b=ind(lst2)
print(abs(a-b))

Submission status: Accepted

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

l = (i+1 for i in range(n))
import itertools
L =[]
for perm in itertools.permutations(l,n):
    L.append(perm)
import bisect

pi = bisect.bisect_left(L,p)
qi = bisect.bisect_left(L,q)

print(abs(qi-pi))

Submission status: Accepted

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

def kaijyo(n):
    if n == 0:
        return 1
    return n * kaijyo(n-1)

def z(n):
    return -n if n<0 else n

def numi(X, y):
    T = sorted(X)
    i = T.index(y)
    #print("#",X,i)
    return i

def solve(N: int, P: "List[int]", Q: "List[int]"):
    ans=0
    for i in range(N):
        ans+=(numi(P[i:], P[i]) - numi(Q[i:], Q[i])) * kaijyo(N - i - 1)
        #print(ans)
    print(z(ans))
    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    Q = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, P, Q)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

perm = permutations([x for x in range(1,N+1)]) 
perm = list(perm)

print(abs((perm.index(P)+1)-(perm.index(Q)+1)))

Submission status: Accepted

Solution code:
n = int(input())
a=list(map(int, input().split()))
b=list(map(int, input().split()))
import itertools

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

permu = list(itertools.permutations(sec))

for i,v in enumerate(permu):
    
    if a == list(v):
        a_i = i+1
    if b == list(v):
        b_i = i+1

print(abs(a_i-b_i))

Submission status: Accepted

Solution code:
from itertools import permutations 

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

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

Submission status: Accepted

Solution code:
import itertools
n = int(input())
s = list(itertools.permutations(range(1,n+1)))
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
aans = 0
bans = 0
for i in s:
  if a == i:
    aans = s.index(a)
  if b == i:
    bans = s.index(b)
print(abs(aans-bans))