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:
def fact(a):
    ret = 1
    for i in range(2,a+1):
        ret *= i
    return ret

def count(a,lst):
    cnt = 0
    for atr in lst:
        if atr < a:
            cnt += 1
    return cnt
N = int(input())
Ps = list(map(int,input().split()))
Qs = list(map(int,input().split()))

a = 1
temp = 0
cntP = 1
for i in range(N):
    if N - 1 - i != 0:
        cntP = cntP + fact(N - 1 - i) * count(Ps[i],Ps[i+1:])

cntQ = 1
for i in range(N):
    if N-1-i != 0:
        cntQ = cntQ + fact(N - 1 - i) * count(Qs[i],Qs[i+1:])

print(abs(cntP-cntQ))

Submission status: Accepted

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

Nlist = [i+1 for i in range(N)]
k = 1
for i in range(N-1):
  k = k * (i+1)
count = 1
for i in range(N):
  n = Nlist.index(P[i])
#  print('n = ', n)
#  print('k = ', k)
  count = n * k + count
  Nlist.remove(P[i])
  if i == N-1:
    break
  else:
    k = k / (N-(i+1))

    
    
Nlist2 = [i+1 for i in range(N)]
k2 = 1
for i in range(N-1):
  k2 = k2 * (i+1)
count2 = 1
for i in range(N):
  n2 = Nlist2.index(Q[i])
#  print('n = ', n2)
#  print('k = ', k2)
  count2 = n2 * k2 + count2
  Nlist2.remove(Q[i])
  if i == N-1:
    break
  else:
    k2 = k2 / (N-(i+1))

#print('count = ', count)
#print('count2 = ', count2)


if count >= count2:
  print(int(count - count2))
if count < count2:
  print(int(count2 - count))


#print('N = ', N)
#print('P = ', P)
#print('Q = ', Q)

Submission status: Accepted

Solution code:
import itertools

N=int(input())
P=tuple(map(int, input().split()))
Q=tuple(map(int, input().split()))
A=list(range(1,N+1))

Pattern=[]
for i in itertools.permutations(A):
    Pattern.append(i)

c1=Pattern.index(P) + 1
c2=Pattern.index(Q) + 1

print(abs(c1-c2))

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)))
p = l.index(P)
q = l.index(Q)
print(abs(p-q))

Submission status: Accepted

Solution code:
f = [0, 1, 2, 6, 24, 120, 720, 5040, 40320]

def get_order(a, n):
    res = 0
    check = [1] * (n + 1)
    check[0] = 0
    for i, c in enumerate(a):
        s = sum(check[:c])
        res += s * f[n - i - 1]
        check[c] = 0
    return res

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

print(abs(get_order(P, N) - get_order(Q, N)))

Submission status: Accepted

Solution code:
import itertools


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

junretsu = itertools.permutations(range(1, n + 1))
junretsu = sorted(junretsu)
a = junretsu.index(p)
b = junretsu.index(q)

print(abs(a - b))

Submission status: Accepted

Solution code:
import random as rng
import itertools as it
import collections as col
import heapq as hq
import sys
import copy as cp
sys.setrecursionlimit(10**9)


def dump_impl(*objects):
    print(*objects, file=sys.stderr)


def dump_dummy(*objects):
    pass


dump = dump_impl if "DEBUG" in sys.argv else dump_dummy

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

factrials = it.permutations(range(1, N+1), N)
a = -1
b = -1
for i, fact in enumerate(it.permutations(range(1, N+1), N)):
    dump(list(zip(list(fact), P)), list(zip(list(fact), Q)))
    if all([x == y for (x, y) in zip(list(fact), P)]):
        a = i
        dump("  a=", a)
    if all([x == y for (x, y) in zip(list(fact), Q)]):
        b = i
        dump("  b=", b)
    dump(fact)
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]

n = ri()
ls1 = ril()
ls2 = ril()

patterns = list(itertools.permutations(range(1, n + 1)))
index1 = patterns.index(tuple(ls1))
index2 = patterns.index(tuple(ls2))
print(abs(index1 - index2))

Submission status: Accepted

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

from itertools import permutations as per
tuples = per(range(1, N+1))

a = 0
b = 0
for i, t in enumerate(tuples):
    if t == P:
        a = i
    if t == Q:
        b = i
print(abs(a - b))

Submission status: Accepted

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

import itertools
L = list(itertools.permutations(l))

jisyo = []
for i in range(len(L)):
  n = 0
  for j in range(N):
    n = n * 10 + L[i][j]
  jisyo.append(n)

p = 0
q = 0
for x in range(N):
  p = p * 10 + P[x]
  q = q * 10 + Q[x]

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

Submission status: Accepted

Solution code:
from itertools import*;(n,),a,b=eval('tuple(map(int,input().split())),'*3);i=list(permutations(range(1,n+1))).index;print(abs(i(a)-i(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()))

    p = 0
    q = 0
    count = 0
    for i in itertools.permutations([i+1 for i in range(N)]):
        if P == list(i):
            p = count + 1
        if Q == list(i):
            q = count + 1
        count += 1
    print(abs(p-q))

    return 0
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import permutations as p
N=int(input())
l=list(p(range(1,N+1)))

A=tuple(map(int, input().split()))
B=tuple(map(int, input().split()))

fa=True
fb=True
for i in range(len(l)):
  if l[i]==A and fa:
    idx_a=i
    fa=False
  if l[i]==B and fb:
    idx_b=i
    fb=False
  if (not fa) and (not fb):
    break
print(abs(idx_a-idx_b))

Submission status: Accepted

Solution code:
from itertools import permutations

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

a, b = 0, 0
for i, v in enumerate(permutations(range(1, N+1), N)):
    if v == P:
        a = i
    if v == Q:
        b = i

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):
    res = 1
    A = [i+1 for i in range(N)]
    for i in range(N):
        A.sort()
        if X[i] != min(A):
            res += factorial(N-(i+1)) * (A.index(X[i]))
        del A[A.index(X[i])]
    return res

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

Submission status: Accepted

Solution code:
from itertools import*;n,*a=open(0);a,b=[list(permutations(range(1,int(n)+1))).index(tuple(map(int,t.split())))for t in a];print(abs(a-b))

Submission status: Accepted

Solution code:
import math
import numpy as np

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

    pe = getal(p)+1
    qe = getal(q)+1
    print(abs(pe-qe))

def getal(arr):
    tarr = arr.copy()
    arg = [None]*len(arr)
    
    c = 0
    for i in range(len(arr)):
        arg[arr.index(min(tarr))] = c
        tarr.remove(min(tarr))
        c += 1

    x = math.factorial(len(arr)-1)

    v = arg[0]*x
    # print(arr, arg, v)

    if len(arr) == 2:
        return v
    else:
        ne = arr[1:]
        return v + getal(ne)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import itertools
import math
n=int(input())
p=tuple(map(int,input().split()))
q=tuple(map(int,input().split()))
l=[]
for i in itertools.permutations(range(1,n+1)):
    l.append(i)
for i in range(math.factorial(n)):
    if l[i]==p:
        a=i+1
    if l[i]==q:
        b=i+1
ans=abs(a-b)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
p=tuple(map(int,input().split()))
q=tuple(map(int,input().split()))
import itertools
seq=tuple([i+1 for i in range(n)])
i=0
for j in itertools.permutations(seq):
  if p==j:
    x=i
  if q==j:
    y=i
  i+=1
print(abs(x-y))

Submission status: Accepted

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

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

p=i.index(P)
q=i.index(Q)
print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools
import math

n = int(input())


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


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

b = []
for i in range(1,len(a)+1):
    b.append(i)

it = itertools.zip_longest(b, a)

pcount = 0
dcount = 0

for i in it:
    if p != d:
        if p == list(i[1]):
            pcount = int(i[0])
        if d == list(i[1]):
            dcount = int(i[0])


print(abs(pcount-dcount))

Submission status: Accepted

Solution code:
from itertools import permutations as p

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
x = y = 0
i = 1
for v in p(list(range(1, n + 1))):
  if list(v) == a:
    x = i
  if list(v) == b:
    y = i
  i += 1
print(abs(x - y))

Submission status: Accepted

Solution code:
import math

N = int(input())

num_p = 1
P = [int(num) for num in input().split(' ')]
nums = [num+1 for num in range(N)]
for i, Pi in enumerate(P):
	nums.remove(Pi)
	num_small = len([num for num in nums if num < Pi])
	num_p += math.factorial(N-i-1)*num_small
        
num_q = 1
Q = [int(num) for num in input().split(' ')]
nums = [num+1 for num in range(N)]
for i, Qi in enumerate(Q):
	nums.remove(Qi)
	num_small = len([num for num in nums if num < Qi])
	num_q += math.factorial(N-i-1)*num_small

print(abs(num_p-num_q))

Submission status: Accepted

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

indp = 1
indq = 1

# pの辞書式順列番号
for i in range(n):
  c = 1
  for j in p[:i]:
    if (j < p[i]):
      c += 1
  indp += math.factorial((n-1)-i) * (p[i]-c)

# qの辞書式順列番号
for i in range(n):
  c = 1
  for j in q[:i]:
    if (j < q[i]):
      c += 1
  indq += math.factorial((n-1)-i) * (q[i]-c)

print(abs(indp-indq))

Submission status: Accepted

Solution code:
import math

def number(plist):
    a = 1
    memo = []
    while len(plist) > 0:
        p = plist.pop(0)
        memo.append(p)
        num = len(set(range(1, p)) - set(memo))
        a += math.factorial(len(plist)) * num
    return a

n = int(input())
plist = list(map(int, input().split()))
qlist = list(map(int, input().split()))

a = number(plist)
b = number(qlist)
print(int(math.fabs(a - b)))

Submission status: Accepted

Solution code:
import math
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 itertools

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

seq = [i for i in range(1,n+1)]
seq_list = list(itertools.permutations(seq))
sorted_seq = sorted(seq_list)

for i in range(len(sorted_seq)):
  if p_list == sorted_seq[i]:
    a = i
  if q_list == sorted_seq[i]:
    b = i
print(abs(a - b))

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import itertools

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

base = list(itertools.permutations(P))
base = sorted(base)

ans = abs(base.index(P) - base.index(Q))

print(ans)

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
nn = sorted(p)
for i in range(n):
  a += (nn.index(p[i])-1) * math.factorial(n-i-1)
  nn.remove(p[i])

nnn = sorted(q)
for j in range(n):
  b += (nnn.index(q[j])-1) * math.factorial(n-j-1)
  nnn.remove(q[j])
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import math

n = int(input())


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


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

b = []
for i in range(1,len(a)+1):
    b.append(i)

it = itertools.zip_longest(b, a)

for i in it:
    if p != d:
        if p == list(i[1]):
            pcount = int(i[0])

        elif d == list(i[1]):
            dcount = int(i[0])

    else:
        pcount = 0
        dcount = 0
        
print(abs(pcount-dcount))

Submission status: Accepted

Solution code:
N = int(input()) 
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
A = list(range(1,N+1))
Alist=[]
import itertools
for v in itertools.permutations(A):
        Alist.append(v)
a_num = Alist.index(P)+1
b_num = Alist.index(Q)+1
print(abs(b_num - a_num))

Submission status: Accepted

Solution code:
import itertools

n=int(input())
a=[]
b=[]
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))

aa=0
bb=0
cou=0
c=[]
for i in range(n):
  c.append(i+1)
  
for x in itertools.permutations(c):
  if a==x:
    aa=cou
  if b==x:
    bb=cou
  cou=cou+1
  
print(abs(aa-bb))

Submission status: Accepted

Solution code:

import itertools
n = int(input())
p = list(map(str,input().split()))
q = list(map(str,input().split()))
a = "".join(p)
b = "".join(q)
l = []
m = []
c = 0
d = ""
x = 0
y = 0

for num in itertools.permutations(p):
    d = "".join(num)
    m.append(d)

l = sorted(m)

x = l.index(a)
y = l.index(b)

print(abs(x-y))

Submission status: Accepted

Solution code:
N = int(input()) 
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
A = list(range(1,N+1))
Alist=[]
import itertools
for v in itertools.permutations(A):
        Alist.append(v)
a_num = Alist.index(P)+1
b_num = Alist.index(Q)+1
print(abs(b_num - a_num))

Submission status: Accepted

Solution code:
import itertools

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

def x(z):
    return sorted(list(itertools.permutations(z))).index(tuple(z)) + 1

x1 = x(b)
x2 = x(c)

print(abs(x1 - x2))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
A = B = 0
for i,v in enumerate(list(itertools.permutations(range(1,N+1))), 1):
    if list(v) == P:
        A = i
    elif list(v) == Q:
        B = i
        continue
print(abs(A-B) if A != 0 and B != 0 else 0)

Submission status: Accepted

Solution code:
import copy

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

def hoge(numbers, s, n_list):

    for i in range(len(numbers)):
        copy_numbers = copy.deepcopy(numbers)
        ss = s+copy_numbers.pop(i)
        if len(copy_numbers) > 0:
            hoge(copy_numbers, ss, n_list)
        else:
            n_list.append(int(ss))

n_list = []
for i in range(n):
    number_list = [str(i) for i in range(1, n+1)]
    s = number_list.pop(i)
    hoge(number_list, s, n_list)

n_list.sort()

ans = abs((n_list.index(p) + 1) - (n_list.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()))
import numpy as np

def stair(N):
  ans=1
  for i in range(1,N+1):
    ans*=i
  return ans

def calc_dict(Q):
  re=list(range(1,len(Q)+1))
  ans=1
  for j in range(len(Q)-1):
    
    if Q[j]!=re[0]:
      a=np.where(np.array(re)<Q[j], 1, 0).sum()
      #print(a)
      ans+=a*stair(len(Q[(j+1):]))
      #print((Q[j]-1)*stair(len(Q[(j+1):])))
      re.remove(Q[j])
    else:
      re.remove(Q[j])
  if ans==0:
    ans+=1
  return ans


print(abs(calc_dict(P_)-calc_dict(Q_)))

Submission status: Accepted

Solution code:
import math


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

    p_pos = get_pos(P)
    q_pos = get_pos(Q)
    if p_pos > q_pos:
        print(p_pos - q_pos)
    else:
        print(q_pos - p_pos)


def get_pos(arr):
    len_to_pattern = [0, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
    p_pos = 0
    pos = len(arr) - 1
    first = len_to_pattern[pos]
    after = list(arr)
    after.sort()
    i = 0
    for p1 in arr:
        p_pos += first * after.index(p1)
        pos -= 1
        first = len_to_pattern[pos]
        i += 1
        after = arr[i:]
        after.sort()
    return p_pos


def get_max_len(l):
    v = l.sort(reverse=True)[0]
    return len(str(v))


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()))
A = B = 0
for i,v in enumerate(list(itertools.permutations(range(1,N+1))), 1):
    if list(v) == P:
        A = i
    elif list(v) == Q:
        B = i
        continue
    else:
        pass
print(abs(A-B) if A != 0 and B != 0 else 0)

Submission status: Accepted

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

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

p=str(math.factorial(n))

a_list = [''.join(v) for v in itertools.permutations(a)]
a_int = [int(i) for i in a_list]
a_int.sort()

a_=[int(i) for i in a]
b_=[int(j) for j in b]
x="".join(a)
y="".join(b)

p_=a_int.index(int(x))+1
q_=a_int.index(int(y))+1

sum=abs(p_-q_)
print(sum)

Submission status: Accepted

Solution code:
import math


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

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



def return_num(numList):

    Flag = []
    for j in range(N):
        Flag.append(1)

    M = 0
    for k in range(N):
        # Flagの1を消去
        Flag[numList[k] - 1] = 0
        M += sum(Flag[:numList[k]-1]) * L[k]


    return M+1



print(abs(return_num(p)-return_num(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()))
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:

import math
import bisect
n= int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
A=0
B=0
for i in range(n-1):
    an=bisect.bisect_left(sorted(a[i:]),a[i])
    # print('an:',an)
    A+= an *math.factorial(n-i-1)
    # print(A)
    bn=bisect.bisect_left(sorted(b[i:]),b[i])

    B+= bn *math.factorial(n-i-1)
    # print(B)

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()))
A = B = 0
for i,v in enumerate(list(itertools.permutations(range(1,N+1))), 1):
    if list(v) == P:
        A = i
    elif list(v) == Q:
        B = i
        continue
    else:
        pass

print(abs(A-B) if A != 0 and B != 0 else 0)

Submission status: Accepted

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

def check_order(k):
    res = 0
    for _ in range(n):
        if len(k) == 1:
            break
        s = k[0]
        c = 0
        for i in k:
            if s >= i:
                 c += 1
        k.pop(0)
        res += math.factorial(len(k)) * (c-1)
    return res

p_order = check_order(p)
q_order = check_order(q)

print(abs(p_order-q_order))

Submission status: Accepted

Solution code:
import math

n = int(raw_input())
p = raw_input().split()
pb = list(range(n))
q = raw_input().split()
qb = list(range(n))

ps = 0
qs = 0

for i in range(n - 1):
    p0 = pb.index(int(p[i]) - 1)
    pb.remove(int(p[i]) - 1)
    ps = (n - i - 1) * (ps + int(p0))

    q0 = qb.index(int(q[i]) - 1)
    qb.remove(int(q[i]) - 1)
    qs = (n - i - 1) * (qs + int(q0))

if qs - ps > 0:
    print qs - ps
else:
    print ps - qs

Submission status: Accepted

Solution code:
import itertools
N=int(input())
A=tuple(map(int, input().split()))
B=tuple(map(int, input().split()))
#print(A,B)
S=list(range(1,N+1)) 
T=list(itertools.permutations(S))
#print(T)
X=T.index(A)
Y=T.index(B)
print(abs(X-Y))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
A = B = 0
for i,v in enumerate(list(itertools.permutations(range(1,N+1))), 1):
    if list(v) == P:
        A = i
    elif list(v) == Q:
        B = i
    else:
        pass

print(abs(A-B) if A != 0 and B != 0 else 0)

Submission status: Accepted

Solution code:
N = int(input())
listA = list(map(int, input().split()))
listB = list(map(int, input().split()))

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


def hatena(list_data, N):
    new_list = []
    index = 0
    for i in range(0, N):
        count = 0
        if list_data[i] == 1:
            new_list.append(1)
            continue
        else:
            for list_el in new_list:
                if list_data[i] > list_el:
                    count += 1
#             print(count)
            index += (list_data[i]-1-count)*exc(N-1-i)
            new_list.append(list_data[i])
    return index

answer = hatena(listA, N) - hatena(listB, N)

# print(hatena(listA, N))
# print(hatena(listB, N))

if answer < 0:
    answer = -answer

print(answer)

Submission status: Accepted

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

P_zero=[i for i in range(1,N+1)]
Q_zero=[j for j in range(1,N+1)]
a=0
b=0
for i in range(N):
    x=N-(i+1)
    fx=math.factorial(x)
    dp=P_zero.index(P[i])
    dq=Q_zero.index(Q[i])
    a+=dp*fx
    b+=dq*fx
    P_zero.remove(P[i])
    Q_zero.remove(Q[i])

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

Submission status: Accepted

Solution code:
from itertools import permutations

N = int(input())
first = tuple(int(i) for i in input().split())
second = tuple(int(i) for i in input().split())

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

Submission status: Accepted

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


N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
X=[0] *N
for idx in range(N):
    X[idx]=factorial_cor(N-1-idx)

Pp = 1
for idx in range(N - 1):
    count = 0
    for idy in range(idx):
        if (P[idx] > P[idy]):
            count+=1
    Pp += ((P[idx] - count - 1) if (P[idx] - count - 1) >= 0 else 0) * X[idx]
Qp = 1
for idx in range(N - 1):
    count = 0
    for idy in range(idx):
        if (Q[idx] > Q[idy]):
            count+=1
    Qp += ((Q[idx] - count - 1) if (Q[idx] - count - 1) >= 0 else 0) * X[idx]

print(abs(Pp-Qp))

Submission status: Accepted

Solution code:
#coding: utf-8

import itertools
from itertools import permutations

def C():
    n = int(raw_input())
    p = list(map(int, raw_input().split()))
    q = list(map(int, raw_input().split()))
    a = 1
    f_a = True
    b = 1
    f_b = True
    for sel in itertools.permutations(range(1,n+1)):
        aa = 0
        bb = 0
        if f_a:
            for i in range(0,n):
                if sel[i] == p[i]:
                    aa = aa + 1
            if aa == n:
                f_a = False
            else:
                a = a + 1
        if f_b:
            for i in range(0,n):
                if sel[i] == q[i]:
                    bb = bb + 1
            if bb == n:
                f_b = False
            else:
                b = b + 1
    print abs(a - b)

if __name__ == '__main__':
    C()

Submission status: Accepted

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

def kaijo(i):
  x = i
  while i > 1:
    i -= 1
    x = x * i
  return x

nokori = list(range(1,N+1))
cnt = 0
for keta in range(1,N+1):
#  print("今は"+str(keta)+"桁目の"+str(P[keta-1])+"を見ています")
#  print("あと"+str(N-keta))
  nokori.sort()
#  print(str(nokori) + "の残りリストの中で何番目に小さいか？")
  banme = nokori.index(P[keta-1])+1
#  print(banme)
  cnt = cnt + kaijo(N-keta) * (banme -1) + 1
  nokori.remove(P[keta-1])
#  print("削除後:"+str(nokori))
#  print("cnt"+str(cnt))
#print(cnt)

nokori = list(range(1,N+1))
cntQ = 0
for keta in range(1,N+1):
#  print("今は"+str(keta)+"桁目の"+str(Q[keta-1])+"を見ています")
#  print("あと"+str(N-keta))
  nokori.sort()
#  print(str(nokori) + "の残りリストの中で何番目に小さいか？")
  banme = nokori.index(Q[keta-1])+1
#  print(banme)
  cntQ = cntQ + kaijo(N-keta) * (banme -1) + 1
  nokori.remove(Q[keta-1])
print(abs(cnt - cntQ))

Submission status: Accepted

Solution code:
N = int(input())
P = input().split()
Q = input().split()
R = [0,0,0,0,0,0,0,0,0]
j = 0
count = 0
sum_P = 0

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

for i in range(N):
    R[int(P[i])] += 1
    for j in range(int(P[i])):
        if R[j+1] == 0:
            count += 1
    sum_P += kaijo(N - i - 1) * count
    count = 0
    j = 0

R = [0,0,0,0,0,0,0,0,0]
j = 0
count = 0
sum_Q = 0

for i in range(N):
    R[int(Q[i])] += 1
    for j in range(int(Q[i])):
        if R[j+1] == 0:
            count += 1
    sum_Q += kaijo(N - i - 1) * count
    count = 0
    j = 0

print(abs(sum_P - sum_Q))

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 fact(n):
    s2=1
    while(n!=0):
        s2=s2*n
        n=n-1
    return(s2)

def count(A):
    s=0
    for i in range(0,N):
        B=sorted(A)
        key=[j for j,e in enumerate(B) if e==A[0]]
        flag=key[0]
        del(A[0])
        del(B[flag])
        s+=flag*(fact(N-1-i))
    return s

p=count(P)
q=count(Q)

if(p>q):
    print(p-q)
else:
    print(q-p)

Submission status: Accepted

Solution code:
import math

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

def min_seq(N):

    Seq = 0
    keta=1
    for i in range (N):
        num = N * keta
        Seq = Seq + num
        N=N-1
        keta=keta*10
    print(Seq)
    return Seq


def connect_PQ(A):
    A_Seq = []
    for i in range (N):
        A_Seq.append(A[i])
    A_Seq = ''.join(A_Seq)
    #print(A_Seq)
    return A_Seq

def sort_seq(A, N):
    sort_num = 1
    for i in range(N):
        alrady_used_num = 0
        for j in range(i):
            if (A[i] > A[j]):
                alrady_used_num = alrady_used_num + 1
        sort_num = sort_num + (A[i]-1-alrady_used_num)*math.factorial(N-1-i)
    #print(sort_num)
    return sort_num


#Seq = min_seq(N)
#P_Seq = connect_PQ(P)
#Q_Seq = connect_PQ(Q)
P_sort_num = sort_seq(P, N)
Q_sort_num = sort_seq(Q, N)

result = abs(P_sort_num - Q_sort_num)
print(result)

Submission status: Accepted

Solution code:
import math

def gosaikutu(nums):
    numbers = list(range(1, len(nums)+1))
    gosa = [0]*len(nums)
    
    for i,number in enumerate(nums):
        gosa[i] = numbers.index(number)
        numbers.remove(number)
    
    return gosa
    
def nanbanme(gosa):
    nanban = 1
    ikutu = len(gosa)
    
    for j,value in enumerate(gosa):
        keisuu = math.factorial(ikutu - j - 1)
        
        if value is not 0:
            nanban += keisuu * value
    return nanban

n = input()
nums1 = list(map(int, input().split(' ')))
nums2 = list(map(int, input().split(' ')))

banme1 = nanbanme(gosaikutu(nums2))
banme2 = nanbanme(gosaikutu(nums1))
ans = banme1 - banme2
if ans < 0:
    print(-ans)
else:
    print(ans)

Submission status: Accepted

Solution code:
import math

N = int(input())

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


def rank(l):
    ll = sorted(l)
    return ll.index(l[0])

ans1 = 0
ans2 = 0
for i in range(N-1):
    ans1 = ans1 + rank(P) * math.factorial(N - i - 1)
    P = P[1:N]
    ans2 = ans2 + rank(Q) * math.factorial(N - i - 1)
    Q = Q[1:N]

if (ans1 - ans2 < 0):
    print(ans2 - ans1)
else:
    print(ans1 - ans2)

Submission status: Accepted

Solution code:
import itertools

n = int(input())

p = list(map(int,input().split()))
q = list(map(int,input().split()))
x = sorted(p)
ans = int(0)

P = tuple(p)
ans1 = int(0)

Q = tuple(q)
ans2 = int(0)

for i in itertools.permutations(x, n):
    if P == i:
        break
    else:
        ans1 += 1

for i in itertools.permutations(x, n):
    if Q == i:
        break
    else:
        ans2 += 1

ans = ans1-ans2

print(abs(ans))