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:
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:
from itertools import permutations
n = int(raw_input())
l1 = raw_input()
l2 = raw_input()
l = []
nLong = [str(i) for i in range(1,n+1)]
pList = permutations(''.join(nLong))
for p in pList: 
	l.append(' '.join(p))
l1 = l.index(l1)
l2 = l.index(l2)
print(abs(l1-l2))

Submission status: Accepted

Solution code:
import math
n = input()
n = int(n)
x = list(map(int,input().split()))
y = list(map(int,input().split()))

def myfunc(a,n):
    c = 0
    while a!=[]:
        c += (a[0]-1)*math.factorial(n-1)
        for i in range(len(a)):
            if a[i]>a[0]:
                a[i] -= 1
        del a[0]
        n -= 1
    return c

print(abs(myfunc(x,n)-myfunc(y,n)))

Submission status: Accepted

Solution code:
import math
import itertools

N = int(input())

PList = tuple(map(int,input().split()))
QList = tuple(map(int,input().split()))

a = list(itertools.permutations(PList))
a.sort()
anum = a.index(PList) + 1
bnum = a.index(QList) + 1

print(abs(int(anum-bnum)))

Submission status: Accepted

Solution code:
import sys

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


last = [n-1 for i in range(n)]

a,b = 0,0

l = [i+1 for i in range(n)]
if l == p:
	a = 1
if l == q:
	b = 1

if a == b == 1:
	print(0)
	sys.exit()
cnt = 1
while True:
	cnt += 1
	for i in range(n-1,-1,-1):
		if l[i] < l[i-1]:
			continue
		else:
			obj = l[i-1]
			tmp = sorted(l[i-1:])
			switch = tmp.pop(tmp.index(obj)+1)
			l = l[:i-1] + [switch] + sorted(tmp)

			#print(l)

			break
	
	if l == p:
		a = cnt
	if l == q:
		b = cnt

	if a != 0 and b != 0:
		break

print(abs(a-b))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 21:29:58 2020

@author: over-
"""

def kai(N):
    a=1
    for n in range(2,N+1):
        a*=n
    return a


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

a,b=0,0


A=[i+1 for i in range(N)]
for i in range(N-1):
    p=int(P[i])
    c=0
    for ai in A:
        if ai < p:
            c+=1
    a+=c*kai(N-i-1)
    A.remove(p)
    
A=[i+1 for i in range(N)]
for i in range(N-1):
    q=int(Q[i])
    c=0
    for ai in A:
        if ai < q:
            c+=1
    b+=c*kai(N-i-1)
    A.remove(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()))
import copy
def count_order(x, n_s):
    ans = 1
    s_ = 1
    y = copy.copy(x)
    for i in x:
        y.remove(i)
        tmp = sum(1 for x in y if x<i) 
        ans += math.factorial(n_s-s_) * tmp
        s_ += 1
    return(ans)
print(abs(count_order(p,n) - count_order(q,n)))

Submission status: Accepted

Solution code:
import itertools

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

p = set(P)
a = 0
b = 0
n = itertools.permutations(p)
ln = []
for v in n:
   ln.append(v)
if P == Q:
  print(0)
else:
  for i in range(0,len(ln)):
    if ln[i] == P:
      a = i+1
    elif ln[i] == Q:
      b = i+1
  print(abs(a-b))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math

n = int(input())

a = list(map(int,input().split()))
b = list(map(int,input().split()))

a_num = 0
b_num = 0
a_li = []
b_li = []

for i in range(n):
  a_li.append(i+1)
  b_li.append(i+1)
  
for i in range(n):
  a_val = a[i]
  a_val2 = 0
  for j in range(len(a_li)):
    if a_li[j] == a_val:
      a_val2 = j
      a_li.remove(a_val)
      break
  a_num += math.factorial(n-i-1) * a_val2     

  b_val = b[i]
  b_val2 = 0
  for j in range(len(b_li)):
    if b_li[j] == b_val:
      b_val2 = j
      b_li.remove(b_val)
      break
  b_num += math.factorial(n-i-1) * b_val2    

print(abs(a_num-b_num))

Submission status: Accepted

Solution code:
from bisect import bisect_left
inpl = lambda: list(map(int,input().split()))
N = int(input())
P = inpl()
Q = inpl()

a = 1
b = 1
M = 1
for i in range(N-2,-1,-1):
    M *= N-1-i
    a += (bisect_left(sorted(P[i:]),P[i]))*M
    b += (bisect_left(sorted(Q[i:]),Q[i]))*M
print(abs(b-a))

Submission status: Accepted

Solution code:
import math
s=int(input())
t=list(map(int,input().split()))
u=list(map(int,input().split()))
def roop1():
  a=0
  for i in range(s):
    c=0
    for j in range(i):
      if t[j]<t[i]:
        c-=1
    c+=(t[i]-1)
    a+=(c)*math.factorial(s-i-1)
  return(a+1)
def roop2():
  b=0
  for i in range(s):
    d=0
    for j in range(i):
      if u[j]<u[i]:
        d-=1
    d+=(u[i]-1)
    b+=(d)*math.factorial(s-i-1)
  return(b+1)
print(abs(roop1()-roop2()))

Submission status: Accepted

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

i = 1

def seed(l):
    if len(l) == 1:
        yield l
        return
    for j in range(len(l)):
        m = l[:j] + l[j + 1:]
        for s in seed(m):
            s = l[j:j + 1] + s
            yield s

i = 1
for s in seed(list(range(1, N + 1))):
    if s == P:
        a = i
    if s == Q:
        b = i
    i += 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()))
arrayp=[1]
for iii in range(n-1):
    arrayp+=[1]
arrayq=[1]
for jjj in range(n-1):
    arrayq+=[1]
pnum=0
qnum=0
for i in range(n-1):
    prank=0
    for ii in range(p[i]):
        if arrayp[ii]==1:
            prank+=1
    pnum=pnum+(prank-1)*math.factorial(n-i-1)
    arrayp[p[i]-1]=0
for j in range(n-1):
    qrank=0
    for jj in range(q[j]):
        if arrayq[jj]==1:
            qrank+=1
    qnum=qnum+(qrank-1)*math.factorial(n-j-1)
    arrayq[q[j]-1]=0
print(abs(pnum-qnum))

Submission status: Accepted

Solution code:
def rec(all_list,num,sl):
    if len(sl)==1:
        all_list.append(num+sl)
        return

    for i,s in enumerate(sl):
        rec(all_list,num+s,sl[:i]+sl[i+1:])

N=int(input())
P=input()[::2]
Q=input()[::2]


all_list=[]

NN=""
for i in range(N):
    NN+=str(i+1)

rec(all_list,"",NN)

for i,s in enumerate(all_list):
    if P==s:
        a=i+1
    
    if Q==s:
        b=i+1

print(abs(a-b))

Submission status: Accepted

Solution code:
N=int(input())
P = input()
Q = input()
P=P.replace(" ","")
Q=Q.replace(" ","")
from itertools import permutations
St = '123456789'
L = list(permutations(St[:N]))
M = [None]*len(L)
for i in range(len(L)):
  M[i]="".join(L[i])
M.sort()
print(abs(M.index(P)-M.index(Q)))

Submission status: Accepted

Solution code:
def fact(x):
    if x==0:
        return 1
    else:
        return x*fact(x-1)


def sea(n,a):
    k=list(range(1,n+1))
    s=0
    for c in range(n):
        j=k.index(a[c])
        s+=j*fact(n-c-1)
        k.remove(a[c])
    return s


n=int(input())
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
print(abs(sea(n,b)-sea(n,a)))

Submission status: Accepted

Solution code:
def count ( n , tpl ) :
	arr = [ x for x in range ( 1 , n+1 ) ] ;
	
	fact = [ 0 for  x in range( n +1 ) ] ; 
	fact[0] = 1 ; 
	for x in range ( 1 , n+1 ) :
		fact[x] = fact[x-1] * x ;
	c = 0 ;
	for idx, x in enumerate(tpl) :
		
		for r in range ( 1 , x ) :
			if r not in arr : continue ;
			c +=  fact[ len(tpl)-idx -1 ] ;
		arr.remove( x ) ;
	return c+ 1 ;

n = int( input().strip() ) ;
t1 = tuple( map ( int , input().strip().split(" ")) ) ;
t2 = tuple( map ( int , input().strip().split(" ")) ) ;
x1 =count( n , t1 ) ;
x2 = count( n , t2 ) ;
print ( abs ( x1 - x2 ) ) ;

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = [tuple(map(int, input().split())) for i in range(1)]
q = [tuple(map(int, input().split())) for i in range(1)]

seq = (1, 2, 3, 4, 5, 6, 7, 8)
seq = seq[:n]

jun = list(itertools.permutations(seq, n))

print(abs(jun.index(p[0]) - jun.index(q[0])))

Submission status: Accepted

Solution code:
from itertools import permutations
r=int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
p = [list(ele) for ele in permutations(range(1,r+1))]
print(abs(p.index(a)-p.index(b)))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = input().replace(' ', '')
q = input().replace(' ', '')
l = sorted(list(itertools.permutations(p, n)))
print(abs(l.index(tuple(p)) - l.index(tuple(q))))

Submission status: Accepted

Solution code:
import itertools

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

R = map(lambda x: x + 1, range(n))

a = 0
b = 0
for i, X in enumerate(itertools.permutations(R)):
  if X == P: a = i
  if X == Q: b = i

if(a >= b): print(a - b)
else: print(b - a)

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
def kaijo(n):
  if n== 1:
    return n
  return n * kaijo(n-1)
N_kaijo = kaijo(N)
a = []
for i in range(N):
  a.append(i+1)
X = list(itertools.permutations(a,N))
p_number = 0
q_number = 0
for i in range(len(X)):
  s = []
  for j in range(N):
    s.append(X[i][j])
  if s == P:
    p_number = i+1
  if s == Q:
    q_number = i+1
if p_number > q_number:
  ans = p_number - q_number
else:
  ans = q_number - p_number
print(ans)

Submission status: Accepted

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


P=[]
P.append(input().split())
P=P[0]
P = [int(i) for i in P]

Q=[]
Q.append(input().split())
Q=Q[0]

Q= [int(i) for i in Q]



result=list(itertools.permutations(P))

x=[]
for i in result:
    x.append(list(i))

x.sort()

numP=x.index(P)+1
numQ=x.index(Q)+1

print(abs(numP-numQ))

Submission status: Accepted

Solution code:
n = int(input())
plist = list(input().split())
qlist = list(input().split())
p = int("".join(plist))
q = int("".join(qlist))

import itertools

nlis = itertools.permutations(range(1, n + 1), n)
nl = [map(str, i) for i in nlis]
nlit = ["".join(i) for i in nl]
nlist = [int(i) for i in nlit]
nlist.sort()

import bisect

pidx = bisect.bisect_left(nlist, p)
qidx = bisect.bisect_left(nlist, q)

print(abs(pidx - qidx))

Submission status: Accepted

Solution code:
import itertools

lists = range(1, int(input()) + 1)
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))

a = 0
b = 0
i = 0
for v in itertools.permutations(lists):
    if v == P:
        a = i
    if v == Q:
        b = i
    if a != 0 and b != 0:
        break
    i += 1

print(abs(b - a))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
#if P == Q:
#  print(0)
#  exit()
a = []
for i in range(N):
  a.append(i + 1)
plist = list(itertools.permutations(a))
print(abs(plist.index(P) - plist.index(Q)))

Submission status: Accepted

Solution code:
import itertools

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

a = 0
b = 0

p_str = "".join(p_list)
q_str = "".join(q_list)
cnt = 0

for n_list in itertools.permutations(range(1, N+1)) :
    n_str = "".join(map(str, n_list))
    if n_str == p_str :
        a = cnt
    if n_str == q_str :
        b = cnt
    cnt += 1

print(abs(a-b))

Submission status: Accepted

Solution code:

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

s = []
for i in a:
  ans = ""
  for j in i:
    ans+=str(j)
  s.append(ans)

P = "".join(list(input().split()))
Q = "".join(list(input().split()))
ans = abs((s.index(P)+1)-(s.index(Q)+1))
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
def f(n):
  if n==1:
    return 1
  else:
    return n*f(n-1)
t1=[0 for i in range(N)]
t2=[0 for i in range(N)]
for i in range(1,N):
  for j in range(i):
    if P[i] > P[j]:
      t1[i]=t1[i]+1
    if Q[i] > Q[j]:
      t2[i]=t2[i]+1 
a=0
b=0
S=f(N)
for i in range(N):
  S=S/(N-i)
  a=a+(P[i]-1-t1[i])*S
  b=b+(Q[i]-1-t2[i])*S
print(int(abs(a-b)))

Submission status: Accepted

Solution code:
def fact(n):
    f = 1
    for i in range(1, n + 1):
        f = f * i
    return f

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

a = 0
b = 0

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

a = a + P[N - 1]
b = b + Q[N - 1]

ans = abs(a - b)

print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations

s = int(input())

alist = [int(x) for x in input().split(maxsplit=(s-1))]
blist = [int(x) for x in input().split(maxsplit=(s-1))]

if alist == blist:
    print(0)
else:
    perm = permutations(sorted(alist))

    count = 1
    a = 0
    b = 0
    for i in list(perm):
        if alist == list(i):
            a = count
            pass
        elif blist == list(i):
            b = count
            pass
        count += 1

    print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
L1 = tuple(map(int,input().split()))
a = 0
L2 = tuple(map(int,input().split()))
b = 0
L = [i for i in range(1,N+1)]
Base = list(itertools.permutations(L))
for i in range(len(Base)):
    if Base[i] == L1:
        a = i+1
for i in range(len(Base)):
    if Base[i] == L2:
        b = i+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()))

def get_num(A,N_list):
    num = 0
    nlist = N_list
    for m in range(n):
        a = N.index(A[m])
        x = a*math.factorial(n-m-1)
        num += x
        nlist.remove(A[m])
    return num

N = list(range(1,n+1))
p = get_num(P,N)
N = list(range(1,n+1))
q = get_num(Q,N)
print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools
import math

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

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

pointer1 = 0
pointer2 = 0

for i,x in enumerate(N_list):
  if x == P:
    pointer1 = i
  if x == Q:
    pointer2 = i
    
print(abs(pointer1 - pointer2))

Submission status: Accepted

Solution code:
import math
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
kai=[math.factorial(i) for i in range(n)]
pl=[i for i in range (1,n+1)]
ql=[i for i in range (1,n+1)]
pc=0
qc=0
countp=0
countq=countp
for i in range(n):
    if p[i]!=pl[0]:
        countp+=pl.index(p[i])*kai[n-i-1]
        del pl[pl.index(p[i])]
    else:
        del pl[0]
for i in range(n):
    if q[i]!=ql[0]:
        countq+=ql.index(q[i])*kai[n-i-1]
        del ql[ql.index(q[i])]
    else:
        del ql[0]
print(abs(countp-countq))

Submission status: Accepted

Solution code:
import itertools
a=int(input())
b=[int(i) for i in input().split()]
c=[int(i) for i in input().split()]
d=[]
for i in range(1,a+1):
    d.append(i)
e=list(itertools.permutations(d))

count_b=0
count_c=0
for i in range(len(e)):
    if list(e[i])==b:
        count_b=i+1
    if list(e[i])==c:
        count_c=i+1
        
ans=count_b-count_c
if ans<0:
    ans*=-1
print(ans)

Submission status: Accepted

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

import itertools

chars = '123456789'

size = int(input())
p = tuple(input().split(' '))
q = tuple(input().split(' '))

values = list(itertools.permutations(chars[:size], size))
index_p = values.index(p)
index_q = values.index(q)

print(abs(index_p - index_q))

Submission status: Accepted

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

BUF_1 = [0] * N
for i in range(N) :
    BUF_1[i] = i+1
buf_2 = 0
buf_3 = 0
buf_4 = 0
j = 0
for i in itertools.permutations(BUF_1) :
    j += 1
    if tuple(P) == i :
        buf_2 = j
        buf_4 += 1
    if tuple(Q) == i :
        buf_3 = j
        buf_4 += 1
    if buf_4 == 2 :
        break

print(abs(buf_2 - buf_3))

Submission status: Accepted

Solution code:
import itertools
import math
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
Nl = list(range(1, N+1))
p = list(itertools.permutations(Nl,N))
NN = math.factorial(N)
c1 = 1
c2 = 1
for v in range(NN):
    if list(p[v]) == P:
        break
    else:
        c1 += 1
for v in range(NN):
    if list(p[v]) == Q:
        break
    else:
        c2 += 1
print(abs(c1-c2))

Submission status: Accepted

Solution code:
import itertools
n=int(input())
cnt=list(itertools.permutations(range(n)))
p=list(map(int,input().split()))
q=list(map(int,input().split()))
for i in range(n):
    p[i]-=1
    q[i]-=1
p=tuple(p)
q=tuple(q)
f=0
for i in range(n):
    if p[i]>q[i]:
        f=1
        break
    elif p[i]<q[i]:
        f=2
        break
    else:
        continue
ans=0
c=0
if f==0:
    print(0)
elif f==1:
    for i in range(len(cnt)):
        if cnt[i]==q:
            c=1
            continue
        if c==1 and cnt[i]!=p:
            ans+=1
        elif c==1 and cnt[i]==p:
            print(ans+1)
            break
elif f==2:
    for i in range(len(cnt)):
        if cnt[i]==p:
            c=1
            continue
        if c==1 and cnt[i]!=q:
            ans+=1
        elif c==1 and cnt[i]==q:
            print(ans+1)
            break
#print(cnt)

Submission status: Accepted

Solution code:
def fr(x):
    if x==0:
        return 0
    o=1
    for i in range(1,x+1):
        o*=i
    return o
        
def nu(x):
    o=0
    y=[0]*n
    for i in range(n):
        for j in range(i):
            if x[i]>x[j]:
                y[i]+=1
    for i in range(n):
        o+=max(0,x[i]-y[i]-1)*fr(n-1-i)
    return o

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

a=nu(p)
b=nu(q)

print(abs(a-b))

Submission status: Accepted

Solution code:
import math

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

a = 0

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


b = 0

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

Submission status: Accepted

Solution code:
# coding UTF-8
# 
# problem C
# 

import itertools

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

seq = tuple(range(1,N+1))
seqlist = list(itertools.permutations(seq))

#print(seqlist)
#print(seqlist.index(P))
#print(seqlist.index(Q))

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

Submission status: Accepted

Solution code:
import itertools

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


pos = 0
pos_p = 0
pos_q = 0
for i in itertools.permutations(range(1,N + 1)):
    pos += 1
    if i == P:
        pos_p = pos
    if i == Q:
        pos_q = pos

print(abs(pos_p - pos_q))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = int(''.join(input().split()))
q = int(''.join(input().split()))


# pcnt = 0
# qcnt = 0
# for i in range(n-3):
#     pcnt += (p[i] - 1 - )*math.factorial(n-i-1)
#     qcnt += (q[i] - 1)*math.factorial(n-i-1)
# ans = abs(pcnt-qcnt)
# print(pcnt,qcnt,ans)

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

for i in range(len(leng)):
    a = int(''.join(map(str,leng[i])))
    # print(a)
    if a == p:
        pcnt = i
    if a == q:
        qcnt = i

ans = abs(pcnt-qcnt)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))

#print(a)
#print(b)

s = 0
aa = 0
bb = 0

p = []
for i in range(1,n+1):
  p.append(i)

import itertools

for v in itertools.permutations(p):
  s += 1
  #print(v)
  if v == a:
    aa = s
  if v == b:
    bb = s
print(str(abs(aa - bb)))

Submission status: Accepted

Solution code:
import sys
import itertools
bbn=1000000007
	
#+++++

def iii(a,b):
	for i,j in zip(a,b):
		if i != j:
			return False
	return True
		
def main():
	n = int(input())
	al = list(map(int, input().split()))
	bl = list(map(int, input().split()))
	cl=al[:]
	cl.sort()
	p=0
	q=0
	i=0
	for ii in itertools.permutations(cl):
		i+=1
		if iii(ii, al):
			p=i
		if iii(ii,bl):
			q=i
		
	print(abs(p-q))
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

Solution code:
import itertools

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


perm = list(range(1,N+1))
perm_list =[]
for v in itertools.permutations(perm,N):
	perm_list.append(v)
a = 0
b = 0
for i in range(len(perm_list)):
	#print(list(perm_list[i]),P)
	perm_list[i] = list(perm_list[i])
	if perm_list[i] == P:
		a = i+1
	if perm_list[i] == Q:
		b = i+1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import math

n=int(input())
p=input().split()
q=input().split()

p0=int(p[0])
q0=int(q[0])

pn=[int(i) for i in p]
qn=[int(i) for i in q]

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

x=[i for i in nums if i!=p0]
p_s=sorted([list(i) for i in itertools.permutations(x, n-1)])
count_x=0
p=int(''.join(p))
for i in p_s:
  if i!=pn[1:]:
    count_x+=1
  else:
    break

y=[i for i in nums if i!=q0]
q_s=sorted([list(i) for i in itertools.permutations(y, n-1)])
count_y=0
q=int(''.join(q))
for i in q_s:
  if i!=qn[1:]:
    count_y+=1
  else:
    break

a=math.factorial(n-1)*(p0-1)+count_x
b=math.factorial(n-1)*(q0-1)+count_y
print(int(((a-b)**2)**0.5))

Submission status: Accepted

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

import itertools

pi = 0
count = 1
for i in itertools.permutations(range(1, n+1), n):
    if list(i) == p:
        pi = count
        break
    else:
        count += 1

qi = 0
count = 1
for i in itertools.permutations(range(1, n+1), n):
    if list(i) == q:
        qi = count
        break
    else:
        count += 1

ans = abs(pi - qi)
print(ans)

Submission status: Accepted

Solution code:
def permutation(lst): 
  
    # If lst is empty then there are no permutations 
    if len(lst) == 0: 
        return [] 
  
    # If there is only one element in lst then, only 
    # one permuatation is possible 
    if len(lst) == 1: 
        return [lst] 
  
    # Find the permutations for lst if there are 
    # more than 1 characters 
  
    l = [] # empty list that will store current permutation 
  
    # Iterate the input(lst) and calculate the permutation 
    for i in range(len(lst)): 
       m = lst[i] 
  
       # Extract lst[i] or m from the list.  remLst is 
       # remaining list 
       remLst = lst[:i] + lst[i+1:] 
  
       # Generating all permutations where m is first 
       # element 
       for p in permutation(remLst): 
           l.append([m] + p) 
    return l 

N = input()
x = [int(x) for x in input().split()]
y = [int(x) for x in input().split()]

NN = list(range(1,int(N)+1))
P = permutation(NN)

xx = P.index(x)
yy = P.index(y)
print(abs(xx-yy))

Submission status: Accepted

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

fact = []
f = 1
for i in range(1,N+1):
    fact.append(f)
    f *= i
fact.reverse()

def dicNum(L):
    ans = 0
    block = N
    l = [i+1 for i in range(N)]
    for i in range(N-1):
        inde = 0
        for j in l:
            if L[i]==j:
                l.pop(inde)
                break
            else:
                inde += 1
        
        ans += fact[i]*inde
    return ans
    
print(abs(dicNum(P)-dicNum(Q)))

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

idx = 1
for i in itertools.permutations(range(1, n + 1)):
    if i == p:
        pi = idx
    if i == q:
        qi = idx
    idx += 1

print(abs(pi - qi))

Submission status: Accepted

Solution code:
import itertools
def main():
    N = int(input())
    A = list(map(int , input().split()))
    B = list(map(int , input().split()))
    #B = input()
    #print (A)
    #print (S)
    #list_N = []
    list_N = list(range(1,N+1))
    #print (list_N)
    #AA = A.index(N) + 1
    #BB = B.index(N) + 1
    #print (AA)
    n1 = 0
    n2 = 0
    count_n = 0
    for i in itertools.permutations(list_N) :
        if A == B :
            print ("0")
            break
        list_i = list(i)
        #print(list_i)
        #print(A)
        count_n = count_n + 1
        if A == list_i :
            n1 = count_n
        elif B == list_i :
            n2 = count_n
        #print (count_n)
    #print (n1)
    #print (n2)
    if A != B :
        print (str(abs(n1 - n2)))


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()))
# Find all possible
perm = list(permutations(range(1,N+1),N))
print(abs(perm.index(P)- perm.index(Q)))

Submission status: Accepted

Solution code:
import math

def function(items, item):
  num = sorted(items)
  num.reverse()
  return num.index(item)+1
   
n = int(input())
p = input().split()
p = [int(_) for _ in p]
q = input().split()
q = [int(_) for _ in q]

items = []
for i in range(n-1):
  items.append(math.factorial(n-i-1))

p_temp = []
for i in range(len(p)):
  p_temp.append((len(p[i:])+1) - function(p[i:], p[i]))

q_temp = []
for i in range(len(q)):
  q_temp.append((len(q[i:])+1) - function(q[i:], q[i]))


p_num = 0
for i in range(len(p)-1):
  t = p_temp[i]-1
  p_num += t*items[i]
  
q_num = 0
for i in range(len(q)-1):
  t = q_temp[i]-1
  q_num += t*items[i]

print(abs(p_num - q_num))

Submission status: Accepted

Solution code:
N = int(input())
P = [int(i) for i in input().split()]
Q = [int(i) for i in input().split()]
a = 0
b = 0
used_a = [True for i in range(N)]
used_b = [True for i in range(N)]
def cal(x,used):
    n = 0
    for i in range(N):
        if used[i] and x > (i+1):
            n += 1
        else:
            pass
    ret = 1
    p = sum(used) - 1
    while True :
        if p == 0 :
            break
        else:
            ret *= p
            p -= 1
    return ret * n

for i in range(N-1):
    a += cal(P[i],used_a)
    used_a[P[i]-1] = False
    b += cal(Q[i],used_b)
    used_b[Q[i]-1] = False
print(abs(a-b))

Submission status: Accepted

Solution code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import pdb
import sys
import math
F = sys.stdin

N = int(F.readline().rstrip())
P = list(map(int,F.readline().rstrip().split()))
Q = list(map(int,F.readline().rstrip().split()))
p_used = []
q_used = []
p_ans = 0
q_ans = 0

for n in range(N):
    p_used.append(P[n])
    for i in range(P[n] - 1):
        if i+1 in p_used:
            continue
        p_ans += math.factorial(N - n - 1)

    q_used.append(Q[n])
    for i in range(Q[n] - 1):
        if i+1 in q_used:
            continue
        q_ans += math.factorial(N - n - 1)


ans = abs(p_ans - q_ans)
# print(p_ans, q_ans)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
def sn(a,n):
  c=0
  for i in a:
    if i<n:
      c+=1
  return c
def comb(n):
  k=1
  if n<=1:
    return 1
  for i in range(1,n+1):
    k=k*i
  return k
def numberorder(a,n):
  s=set({})
  for i in range(1,n+1):
    s=s|{i}
  c=0
  for p in range(n):
    c+=(sn(s,a[p]))*comb(n-1-p)
    s=s-{a[p]}
  return c
P_num=numberorder(P,N)
Q_num=numberorder(Q,N)
print(abs(P_num-Q_num))

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
import math
def top(A):
    s = 0
    for i in range(0,len(A)):
        if A[i] > A[0]:
            s = s + 1
    return s
def count(A):
    t = 0
    for i in range(1,N):
        t = t + top(A) * math.factorial(N-i)
        A.pop(0)
    return t
a = abs(count(P)-count(Q))
print(a)

Submission status: Accepted

Solution code:
import math
n=int(input())
plis=list(map(int,input().split()))
qlis=list(map(int,input().split()))
acounter=0
bcounter=0
pdic=[]
qdic=[]
for i in range(1,n+1):
	pdic.append(i)
	qdic.append(i)
for i in range(n):
	a=int((math.factorial(n-i)/(n-i))*(pdic.index(plis[i])))
	acounter+=a
	pdic.remove(plis[i])
	b=int((math.factorial(n-i)/(n-i))*(qdic.index(qlis[i])))
	bcounter+=b
	qdic.remove(qlis[i])
print(abs((acounter+1)-(bcounter+1)))

Submission status: Accepted

Solution code:
import math

N = int(input())
P_str = input().split()
P = [int(p) for p in P_str]
Q_str = input().split()
Q = [int(q) for q in Q_str]

pnumber = [m for m in range(1, N+1)]
qnumber = [m for m in range(1, N+1)]

pnum = 1
qnum = 1

for i in range(N):
    pnum += pnumber.index(P[i])*math.factorial(N-i-1)
    pnumber.remove(P[i])
    
for i in range(N):
    qnum += qnumber.index(Q[i])*math.factorial(N-i-1)
    qnumber.remove(Q[i])

print(abs(pnum-qnum))

Submission status: Accepted

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

import itertools

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

zyu = itertools.permutations(l, n)

for t, child in enumerate(zyu):
    p_flag = True
    q_flag = True
    for check_idx in range(0, n):
        if list(child)[check_idx] == p[check_idx]:
            pass
        else:
            p_flag = False
            break

    for check_idx in range(0, n):    
        if list(child)[check_idx] == q[check_idx]:
            pass
        else:
            q_flag = False
            break

    if p_flag:
        p_idx = t+1

    if q_flag:
        q_idx = t+1



print(abs(q_idx-p_idx))