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:
N = int(input())
Ps = list(map(int, input().split()))
Qs = list(map(int, input().split()))


cnt = 0
start = 0
end = 0
is_hit = False
for i in range(1,N+1):
    for j in range(1,N+1):
        if j in [i]:
            continue
        if N == 2:
            cnt += 1
        if [i, j] == Ps:
            start = cnt
        if [i, j] == Qs:
            end = cnt
        if start * end > 0:
            is_hit = True
            break
        if N == 2:
            continue
        for k in range(1,N+1):
            if k in [i, j]:
                continue
            if N == 3:
                cnt += 1
            if [i, j, k] == Ps:
                start = cnt

            if [i, j, k] == Qs:
                end = cnt
            if start * end > 0:
                is_hit = True
                break
            if N == 3:
                continue
            for l in range(1,N+1):
                if l in [i, j, k]:
                    continue
                if N == 4:
                    cnt += 1
                if [i, j, k, l] == Ps:
                    start = cnt

                if [i, j, k, l] == Qs:
                    end = cnt

                if start * end > 0:
                    is_hit = True
                    break

                if N == 4:
                    continue
                for m in range(1, N+1):
                    if m in [i, j, k, l]:
                        continue
                    if N == 5:
                        cnt += 1
                    if [i, j, k, l, m] == Ps:
                        start = cnt
                    if [i, j, k, l, m] == Qs:
                        end = cnt

                    if start * end > 0:
                        is_hit = True
                        break

                    if N == 5:
                        continue
                    for n in range(1, N+1):
                        if n in [i, j, k, l, m]:
                            continue
                        if N == 6:
                            cnt += 1
                        if [i, j, k, l, m, n] == Ps:
                            start = cnt
                        if [i, j, k, l, m, n] == Qs:
                            end = cnt
                        if start * end > 0:
                            is_hit = True
                            break
                        if N == 6:
                            continue
                        for o in range(1, N+1):
                            if o in [i, j, k, l, m, n]:
                                continue
                            if N == 7:
                                cnt += 1
                            if [i, j, k, l, m, n, o] == Ps:
                                start = cnt
                            if [i, j, k, l, m, n, o] == Qs:
                                end = cnt
                            if start * end > 0:
                                is_hit = True
                                break
                            if N == 7:
                                continue
                            for p in range(1, N+1):
                                if p in [i, j, k, l, m, n, o]:
                                    continue
                                if N == 8:
                                    cnt += 1
                                if [i, j, k, l, m, n, o, p] == Ps:
                                    start = cnt
                                if [i, j, k, l, m, n, o, p] == Qs:
                                    end = cnt
                                if start * end > 0:
                                    is_hit = True
                                    break
                            if is_hit:
                                break
                        if is_hit:
                            break
                    if is_hit:
                        break
                if is_hit:
                    break
            if is_hit:
                break
        if is_hit:
            break
    if is_hit:
        break

print(abs(end - start))

Submission status: Accepted

Solution code:
import sys
import math
input = sys.stdin.readline


def main():
    sc = Scan()
    N = sc.intarr()[0]
    P = sc.intarr()
    Q = sc.intarr()
    p_idx = -1
    q_idx = -1
    roop = 0
    array = []
    for i in range(1, N+1):
        array.append(i)
    pp = perm(array)
    for p in pp:
        if p == P:
            p_idx = roop
        if p == Q:
            q_idx = roop
        roop += 1

    print(abs(p_idx-q_idx))


def perm(p):
    if len(p) == 1:
        return [p]
    else:
        s = []
        for i in range(len(p)):
            q = p[i]
            r = perm(p[:i]+p[i+1:])
            for t in r:
                s.append([q] + t)
        return s


class Scan():

    def intarr(self):
        num_array = list(map(int, input().split()))
        return num_array

    def intarr_ver(self, n):
        return [int(input()) for _ in range(n)]

    def strarr(self):
        line = input()
        array = line.split(' ')
        array[-1] = array[-1].strip('\n')
        return array


def display(array):
    for a in range(len(array)):
        if len(array) - a != 1:
            print(array[a], end=' ')
        else:
            print(array[a])


def gcd(a, b):  # 最大公約数
    while b:
        a, b = b, a % b
    return a


def lcm(a, b):  # 最小公倍数
    return a * b // gcd(a, b)


main()

Submission status: Accepted

Solution code:
import numpy
import itertools
N=int(input())
p=list(map(int, input().split()))
q=list(map(int, input().split()))
value = 1
count=0
second_box =[]
box = [i for i in range(1,N+1)]
value = list(itertools.permutations(box))
#print(value)
def func(i):
    rs = 0
    for j in range(N):
        rs += i[j] * 10**(N-j-1)
    return rs 
  
second_box = [ func(i) for i in value]
#second_box = [a = numpy.random.choice(box,size=N,replace=False,p=None) ]

#n_second_box = [func(i) for i in second_box]
third_box = sorted(second_box,reverse=False)
#print((third_box))
a = third_box.index(func(p))
b = third_box.index(func(q))
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
L=[]
sum=0
for i in range(1,N+1):
    L.append(i)
M=list(itertools.permutations(L))
for i in M:
    if P == i:
        seterP=(M.index(i))
    if Q == i:
        seterQ=(M.index(i))
if seterP>=seterQ:
    print(seterP-seterQ)
else:
    print(seterQ-seterP)

Submission status: Accepted

Solution code:
import itertools 

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

arrayForPerm = []

for i in range(1,N+1):
  arrayForPerm.append(i)
  
perm = itertools.permutations(arrayForPerm)
newPerm = list(perm)

for i in range(len(newPerm)):
  if list(newPerm[i]) == P:
    A = i + 1
  if list(newPerm[i]) == Q:
    B = i + 1

result = A - B

print(abs(result))

Submission status: Accepted

Solution code:
n = int(input())
x = map(int, input().split()[:n-1])
y = map(int, input().split()[:n-1])
if x == y:
    print(0)
else:
    l1 = [i for i in range(1, n+1)]
    l2 = list(l1)
    def fact(k):
        return 1 if k <= 1 else k * fact(k-1)

    def get_lex_order(n, l, z):
        t = 0
        for i, m in enumerate(z):
            k = l.index(m)
            l.remove(m)
            t += k * fact(n - i - 1)
        return t + 1
    print(abs(get_lex_order(n, l1, x) - get_lex_order(n, l2, y)))

Submission status: Accepted

Solution code:
import itertools
import re

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

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

conv =[]
for v in itertools.permutations(n_list, n):
    conv.append(v)

for i, j in enumerate(conv):
    if p == j:
        p_ind = i + 1

for i, j in enumerate(conv):
    if q == j:
        q_ind = i + 1

print(abs(p_ind - q_ind))

Submission status: Accepted

Solution code:
import sys
from functools import reduce
import itertools


input = sys.stdin.readline

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

if (P == Q):
    print(0)
else:
    res = list(filter(lambda t: t[1] == P or t[1] == Q, enumerate(itertools.permutations(range(1, N + 1)))))

    print(abs(res[0][0] - res[1][0]))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import numpy as np

n = int(input())
p = np.array(input().split(), dtype='int')
q = np.array(input().split(), dtype='int')

kaijou = np.array([1, 2, 6, 24, 120, 720, 5040])

a = 1
b = 1

num_array = np.arange(1, n + 1)
for i in range(n - 1):
    for j in range(n - i):
        if p[i] == num_array[j]:
            k = j
    a += k * kaijou[n - i - 2]
    num_array = np.delete(num_array, k)


num_array = np.arange(1, n + 1)
for i in range(n - 1):
    for j in range(n - i):
        if q[i] == num_array[j]:
            k = j
    b += k * kaijou[n - i - 2]
    num_array = np.delete(num_array, k)

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

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
def fact(a):
    if a == 1:
        return 1
    else: return a * fact(a-1)
def orde(s):
    y = 1
    for i in range(len(s)-1):
        y += fact(len(s)-i-1) * (s[i]-1)
        for j in range(i, len(s)):
            if s[j] > s[i]:
                s[j] -= 1
    return y
print(abs(orde(p)-orde(q)))

Submission status: Accepted

Solution code:
import itertools

N = list(map(int, input().split()))
permutation_P = tuple(map(int, input().split()))
permutation_Q = tuple(map(int, input().split()))

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

dictionaly = list(itertools.permutations(data))
dic_size = len(dictionaly)

for j in range(0, dic_size):
    if permutation_P == dictionaly[j] and permutation_Q == dictionaly[j]:
        a = j + 1
        b = j + 1
    elif permutation_P == dictionaly[j]:
        a = j + 1
    elif permutation_Q == dictionaly[j]:
        b = j + 1

if (a - b) >=  0:
    print(a - b)
elif (a - b) < 0:
    print(-1 * (a - b))

Submission status: Accepted

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

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

def hoge(n,lis):
    for i in range(len(lis)):
        if n==lis[i]:
            return i
        
def cnt(lis):
    #input: list
    l = list(range(1,len(lis)+1)) #[1,2,...,n]
    ret = 1
    for i in range(len(lis)-1):
        ret += (hoge(int(lis[i]),l)) * fact(len(l)-1)
#         print((int(lis[i])-1) * fact(len(l)-1))
        l.remove(lis[i])
#         print(l)
    return ret

print(abs(cnt(P) - cnt(Q)))

Submission status: Accepted

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

from itertools import permutations

t = [i for i in range(1, N+1)]
r = list(permutations(t))

# print(P)
# print(Q)

i1 = r.index(P)
i2 = r.index(Q)
print(abs(i1-i2))

Submission status: Accepted

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

def kaijou(n):
    s = 1
    for i in range(n):
        s *= i+1
    return s

def jisyo(L):
    l = 0
    k = len(L)
    for i in range(k):
        n = L.pop(0)
        l += kaijou(len(L))*(n-1)
        for m in range(len(L)):
            if L[m] > n:
                L[m] -= 1
    return l+1

print(abs(jisyo(P)-jisyo(Q)))

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 = b  = count= 0

org = sorted(p)

for v in itertools.permutations(org,n):
    count += 1
    
    if list(v)==p:
        a = count
    
    if list(v)==q:
        b = count

print(abs(a - b))

Submission status: Accepted

Solution code:
def kaijo(x):
  if x<=1:
    return 1
  elif x==2:
    return 2
  elif x==3:
    return 6
  elif x==4:
    return 24
  elif x==5:
    return 120
  elif x==6:
    return 720
  elif x==7:
    return 5040
  elif x==8:
    return 5040*8
  else:
    return 0

N=int(input())
s=input().split(" ")
P=[int(ss) for ss in s]
s=input().split(" ")
Q=[int(ss) for ss in s]

Ls=[i+1 for i in range(N)]
rank=0
for i in range(N):
  for j in range(len(Ls)):
    if Ls[j]==P[i]:
      a=j
      Ls.pop(j)
      break
  rank+=kaijo(N-i-1)*a
rp=rank

rank=0
Ls=[i+1 for i in range(N)]
#print(Ls)
for i in range(N):
  for j in range(len(Ls)):
    if Ls[j]==Q[i]:
      a=j
      Ls.pop(j)
      break
  rank+=kaijo(N-i-1)*a
rq=rank
#print(rank)
print(abs(rp-rq))

Submission status: Accepted

Solution code:
r = int(input())
tp = tuple(map(int,input().split()))
tq = tuple(map(int,input().split()))

import itertools

p, q = 0, 0 
for i, ti in enumerate(itertools.permutations(range(1,r+1))):
    if tp == ti:
        p = i        
    if tq == ti:
        q = i
    if p * q > 0:
        break

print(abs(p-q))

Submission status: Accepted

Solution code:
import math

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
  
a = list(range(1, n+1))
b = list(range(1, n+1))
nump = 1
numq = 1

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

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

print(abs(nump - numq))

Submission status: Accepted

Solution code:
import math
import copy

n = int(input())
ls_p = list(map(int, input().split()))
ls_q = list(map(int, input().split()))

ls_pc = copy.copy(ls_p)
ls_qc = copy.copy(ls_q)

s = 0
t = 0

ansp = 0
ansq = 0

for i in range(n):
    s = ls_pc[i]
    ls_ps = sorted(ls_p)
    j = ls_ps.index(s)
    ansp += math.factorial(n - i - 1) * j
    ls_p.remove(s)
    
    t = ls_qc[i]
    ls_qs = sorted(ls_q)
    k = ls_qs.index(t)
    ansq += math.factorial(n - i - 1) * k
    ls_q.remove(t)

print(abs(ansp - ansq))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
li_p = input().split()
li_q = input().split()

li_p = tuple(li_p)
li_q = tuple(li_q)

li_min = sorted(li_p)
list_all = []

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

for i in range(0, len(list_all)):
    if list_all[i] == li_p:
        count_p = i
    if list_all[i] == li_q:
        count_q = i

print(abs(count_p - count_q))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
T = list(range(1,N+1))
S = list(itertools.permutations(T, N))
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]

for i in range(len(S)):
    if tuple(P) == S[i]:
        A = i
    if tuple(Q) == S[i]:
        B = i
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()))


a = list(itertools.permutations(p))
b = list(itertools.permutations(q))

a.sort()
b.sort()

ans1 = a.index(p) + 1
ans2 = b.index(q) + 1

print(abs(ans1 - ans2))

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:
n = int(input())
p = [int(v) for v in input().split()]
q = [int(v) for v in input().split()]

def index_of(array, v):
    for i in range(len(array)):
        if v == array[i]:
            return i
    return -1

def perm(v):
    p = 1
    for i in range(2, v+1):
        p *= i
    return p

memo = [1] * (n+1)
for i in range(1, n+1):
    memo[i] = perm(i)
    #print("P!: ", i, memo[i])

def to_n(array):

    m = 0
    sa = sorted(array)
    while len(array) > 0:
        v = array.pop(0)
        index = index_of(sa, v)
        k = len(array)
        #print("v: ",v, ", index: ", index, ", memo: ", memo[k], index * memo[k])
        m += index * memo[k]

        if k == 0:
            break
        sa = sorted(array)

    return m

a = to_n(p)
#print("a", a)

b = to_n(q)
#print("b", b)
print(abs(a - b))

Submission status: Accepted

Solution code:
import math
import itertools

N = int(input())

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

tP = tuple(P)
tQ = tuple(Q)
ord_P = 0 
ord_Q = 0 
cnt = 1
Num = []


for i in itertools.permutations(range(1,N+1)): 
    if i == tP:
        ord_P = cnt
    if i == tQ:
        ord_Q = cnt
    cnt += 1
    
print(abs(ord_P - ord_Q))

Submission status: Accepted

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

import itertools
a = tuple(i for i in range(1,n+1))
x = list(itertools.permutations(a))
#print(x)
px = x.index(p)
qx = x.index(q)
print(abs(px-qx))

Submission status: Accepted

Solution code:
import math
 
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
 
p_sort = sorted(p)
q_sort = sorted(q)
 
p_number = 1
q_number = 1
 
k = 0
for i in p:
  k += 1
  i_index = p_sort.index(i)
  p_number += i_index * math.factorial(n-k)
  p_sort.remove(i)
k = 0
for i in q:
  k += 1
  i_index = q_sort.index(i)
  q_number += i_index * math.factorial(n-k)
  q_sort.remove(i)
answer = abs(p_number - q_number)
print(answer)

Submission status: Accepted

Solution code:
r = int(input())
tp = tuple(map(int,input().split()))
tq = tuple(map(int,input().split()))

import itertools

for i, ti in enumerate(itertools.permutations(range(1,r+1))):
    if tp == ti:
        p = i
        break

for i, ti in enumerate(itertools.permutations(range(1,r+1))):
    if tq == ti:
        q = i
        break

print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools

num = int(input())

kizyun = [i+1 for i in range(num)]

retu = list(itertools.permutations(kizyun, num))  

tansaku1 = input().split()
for i in range(len(tansaku1)):
  tansaku1[i] = int(tansaku1[i])
tansaku1 = tuple(tansaku1)

tansaku2 = input().split()
for i in range(len(tansaku2)):
  tansaku2[i] = int(tansaku2[i])
tansaku2 = tuple(tansaku2)

a = 0
b = 0

for i in range(len(retu)):
  if retu[i] == tansaku1:
    a = i+1
  if retu[i] == tansaku2:
    b = i+1

ans = abs(a-b)

print(ans)

Submission status: Accepted

Solution code:
import math

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
per = math.factorial(n - 1)
r = 0
r2 = 0
for k in range(1, n)[::-1]:
    t = p[0]
    c = sum([t > x for x in p])
    r += per * c
    p.remove(t)
    t = q[0]
    c = sum([t > x for x in q])
    r2 += per * c
    q.remove(t)
    per = int(per / k)

print(int(abs(r - r2)))

Submission status: Accepted

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

def DicNum(P,n): #nがPの何番目か
    count = 0
    for i in range(len(P)):
        if n < P[i]:
            count += 1
    return count

def DicNumP(P): #Pが何番目か
    count = 0
    for i in range(len(P)):
        count += DicNum(P[i:],P[i])*math.factorial(N-i-1)
    return count

print(abs(DicNumP(P)-DicNumP(Q)))

Submission status: Accepted

Solution code:
import math

N = int(input())
A = 0
B = 0
a = list(map(int,input().split()))
b = list(map(int,input().split()))
a_num = [i+1 for i in range(N)]
b_num = [i+1 for i in range(N)]

for i in range(N):
    a_idx = a_num.index(a[i])
    b_idx = b_num.index(b[i])
    a_num.pop(a_idx)
    b_num.pop(b_idx)

    A = A + math.factorial(N-i)*((a_idx)/(N-i))
    B = B + math.factorial(N-i)*((b_idx)/(N-i))


print("{}".format(int(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 f(l):
    return math.factorial(l)
a = 0
b = 0
R = [1,2,3,4,5,6,7,8,9]
S = [1,2,3,4,5,6,7,8,9]
for i in range(n):
    c = R.index(P[i])
    a += f(n-i-1)*(c-1)
    R.remove(P[i])
for i in range(n):
    d = S.index(Q[i])
    b += f(n-i-1)*(d-1)
    S.remove(Q[i])
print(abs(a-b))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
from itertools import permutations

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

array = [item for item in range(1, n+1)]

for i, perm in enumerate(permutations(array)):
    if perm == p:
        frm = i
    if perm == q:
        to = i
print(abs(frm - to))

Submission status: Accepted

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

dict = {}
d = [i for i in range(1,n+1)]
i = 1
for x in permutations(d,n):
    dict[x] = i
    i += 1

print(abs(dict[P]-dict[Q]))

Submission status: Accepted

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

p_list = list(itertools.permutations(p, n))
p_list.sort()
a = p_list.index(p)
b = p_list.index(q)

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
#import math

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

p = input()
q = input()
#print(n)
#print(p)
i = 0
#a = 0 
#b = 0

for x in itertools.permutations(range(1,n+1), n):
	#print(x)
	x = " ".join(map(str,x))
	#print(x)
	i += 1
	if x == p:
		a = i
		#print(i)
	if x == q:
		b = i
		#print(i)

print(abs(a-b))

Submission status: Accepted

Solution code:
#c
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)]
i=0
a=0
b=0
for x in itertools.permutations(num,n):
    i+=1
    
    if x==p:
        a=i
    if x==q:
        b=i
ans=abs(a-b)
print(ans)

Submission status: Accepted

Solution code:
import itertools
import numpy as np
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
count = 0
a = 0
b = 0
num = []
for i in range(1,n+1):
    num.append(i)
for balls in itertools.permutations(num):
    count = count + 1
    if(list(balls) == p):
         a = count
    if(list(balls) == q):
         b = count
print(np.abs(a-b))

Submission status: Accepted

Solution code:
import math

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

a = 0

for i, p in enumerate(P, start=1):
  for j in range(1, p):
    if not j in P[:i-1]:
    	a += math.factorial(N-i)
    
b = 0

for i, q in enumerate(Q, start=1):
  for j in range(1, q):
    if not j in Q[:i-1]:
      b	+= math.factorial(N-i)

sum = a - b
if sum < 0:
  sum *= -1

print(sum)

Submission status: Accepted

Solution code:
import math
 
def dic(s):
  l = len(s)
  if l == 0:
    return 0
  c = s[0]
  tmp = ((sorted(s)).index(c)-1) * math.factorial(l -1)
  return tmp + dic(s[1:])
 
n = input()
s1 = list(map(int, input().split()))
s2 = list(map(int, input().split()))
 
print(abs(dic(s1)-dic(s2)))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import math

n = int(input())
r = []
p = list(map(int, input().split()))
q = list(map(int, input().split()))
for i in range(n):
    r.append(i+1)

count =0
a=1
b=1
while(count<n):
    for i in r:
        if p[count] ==i :
            count+=1
            r.remove(i)
            break;
        else:
            a+=math.factorial(n-count-1)
r = [] 
for i in range(n):
    r.append(i+1)
count = 0
while(count<n):
    for i in r:
        if q[count] ==i :
            count+=1
            r.remove(i)
            break;
        else:
            b+=math.factorial(n-count-1)           
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

total = int(input())
text_1 = list(map(int, input().split()))
text_2 = list(map(int, input().split()))
text_1_join = int("".join([str(x) for x in text_1]))
text_2_join = int("".join([str(x) for x in text_2]))

text_1_sort = sorted(text_1)
target = list(itertools.permutations(text_1_sort))
target_join = [int("".join(str(y) for y in x)) for x in target]

get_index_1 = target_join.index(text_1_join) + 1
get_index_2 = target_join.index(text_2_join) + 1

print(abs(get_index_1 - get_index_2))

Submission status: Accepted

Solution code:
import itertools
from math import factorial

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
f = factorial(N)
all = list(itertools.permutations(range(1,N+1), N))

count = 0
for i in range(f):
        if all[i] == P:
                count += i+1
        if all[i] == Q:
                count -= i+1

print(abs(count))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
#C
import itertools
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
A=[]
for i in range(1,N+1):
    A.append(i)
#print(A)

A=list(itertools.permutations(A))
#print(A)
#print(tuple(P))
#print(tuple(Q))
M=1
for i in range(1,N+1):
    M*=i
for i in range(M):
    if A[i]==tuple(P):
        a=i+1
    if A[i]==tuple(Q):
        b=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()))

for i, p in enumerate(itertools.permutations(range(1, N + 1))):
    if p == P:
        pi = i + 1
    if p == Q:
        qi = i + 1

print(abs(pi - qi))

Submission status: Accepted

Solution code:
import numpy as np
import math

n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
enda = list([n+1])
endb = list([n+1])
numa = 0
numb = 0

for i in range(0,n-1):
  enda.append(a[i])
  endb.append(b[i])
  aa,bb = 0,0
  for j in range(0,i+1):
    if enda[j] < a[i]:
      aa += 1 
  a[i] = a[i] - aa
  for j in range(0,i+1):
    if endb[j] < b[i]:
      bb += 1
  b[i] = b[i] - bb
  
  numa += (a[i] -1) * math.factorial(n-1-i)
  numb += (b[i] -1) * math.factorial(n-1-i)

print(abs(numa - numb))

Submission status: Accepted

Solution code:

def insert_string_to_base(target_string, insert_point, insert_string):
    return target_string[:insert_point] + insert_string + target_string[insert_point:]

input1=input()
input2=input()
input3=input()

N=int(input1)

P=""
for i in range((len(input2)+1)//2):
    P+=input2[2*i]
Q=""
for i in range((len(input3)+1)//2):
    Q+=input3[2*i]



def permutate(n):
    ans=[]
    if n==1:
        ans=["1"]
    else:
        temp=permutate(n-1)

        for t in temp:
            for i in range(len(t)+1):
                tm=insert_string_to_base(t,i,"{}".format(n))
                ans.append(tm)

    return ans

arr=permutate(N)

ARR=sorted(arr)

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
N=[i for i in range(1,n+1)]
p1=[i for i in range(1,n+1)]
q1=[i for i in range(1,n+1)]
def kaijou(x):
    if x==0:
        return 0
    elif x==1:
        return 1
    elif x==2:
        return 2
    elif x==3:
        return 6
    elif x==4:
        return 24
    elif x==5:
        return 120
    elif x==6:
        return 720
    elif x==7:
        return 5040

s1=1
s2=1
j=1
for i in p:
    s1 += kaijou(n-j)*int(p1.index(i))
    j+=1
    p1.remove(i)
j=1
for i in q:
    s2 += kaijou(n-j)*int(q1.index(i))
    j+=1
    q1.remove(i)
k=s1-s2
if k<0:
    print(-k)
else:
    print(k)

Submission status: Accepted

Solution code:
def factlist(n):
  res = [1]
  for i in range(n):
    res.append(res[i] * (i+1))
  return res

def dic_ord(n, a):
  fact = factlist(n-1)
  b = list(range(1, n+1))
  res = 0
  for i in range(n-1):
    j = b.index(a[i])
    res += fact[n-i-1] * j
    b.pop(j)
  return res

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

print(abs(dic_ord(n, a)-dic_ord(n, 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()]
def count(U):
    S = sorted(U)
    C = 1
    for i,j in enumerate(U):
        c = 0
        for u,v in enumerate(S):
            if v == j:
                del S[u]
                break
            else:
                c += 1
        C += (math.factorial(N-i-1))*c
    return C
print(abs(count(P)-count(Q)))

Submission status: Accepted

Solution code:
import math

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

ans_P = 0
for i in range(N):
    P_sort = sorted(P)
    a = P_sort.index(P[0])
    n = math.factorial(N-1-i)*a
    ans_P += n
    del P[0]

ans_Q = 0
for i in range(N):
    Q_sort = sorted(Q)
    a = Q_sort.index(Q[0])
    n = math.factorial(N-1-i)*a
    ans_Q += n
    del Q[0]

print(abs(ans_Q - ans_P))

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