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:
#!/usr/bin/env python3
import sys
import math



def f(a):
    res = 1
    used = []
    for i in range(len(a)):
        x = 1
        c = 0
        while x != a[i]:
            f = 1
            for j in range(i):
                if a[j] == x:
                    f = 0
                    break
            if f == 1:
                c += 1
            x += 1

        res += c * math.factorial(len(a) - i - 1)
    return res








def solve(N: int, P: "List[int]", Q: "List[int]"):
    print(abs(f(P) - f(Q)))
    return


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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def generate_perms(n, perms):
    if n == 0:
        return perms
    new_perms = []
    for perm in perms:
        for i in range(1, N+1):
            if i not in perm:
                p = list(perm)
                p.append(i)
                new_perms.append(p)
    return generate_perms(n-1, new_perms)


N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
perms = generate_perms(N, [[]])
print(abs(perms.index(P) - perms.index(Q)))

Submission status: Accepted

Solution code:
import math

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


def get_digit_order(digit, found_list):
    count = 0
    select = 1
    while select != digit:
        if select not in found_list:
            count += 1
        select += 1
    return count


def get_order(num_list):
    found = []
    order = 0
    for i in range(N - 1):
        digit_count = get_digit_order(num_list[i], found)
        found.append(num_list[i])
        order += math.factorial(N - i - 1) * digit_count
    return order


a = get_order(A)
b = get_order(B)

print(abs(a - b))

Submission status: Accepted

Solution code:
from math import factorial
N = int(input())
Plist = list(map(int, input().split()))
Qlist = list(map(int, input().split()))


def get_rank(array):
    nokori = list(range(1, N + 1))
    ans = 0
    for i in range(N - 1):
        num = N - i - 1
        ans += factorial(num) * nokori.index(array[i])
        nokori.remove(array[i])
    return ans + 1

a = get_rank(Plist)
b = get_rank(Qlist)
print(abs(a - b))

Submission status: Accepted

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

from itertools import permutations
s = [i for i in range(1,N+1)]

Ps = [i for i in P]
Qs = [i for i in Q]

a = 0
b = 0
for i,t in enumerate(permutations(s)):
    ts = list(t)
    if Ps == ts:
      a = i
    if Qs == ts:
      b = i
      
ans = abs(a-b)
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()))

per_s = permutations(range(1, n+1))

c1 = 0
c2 = 0
for i, per in enumerate(per_s):
    if (per == p):
        c1 = i
    if (per == q):
        c2 = i

print(abs(c1 - c2))

Submission status: Accepted

Solution code:
def fact(n):
    f = 1
    while n >= 1:
        f = f * n
        n = n - 1
    return f


def findSmallerInRight(st, low, high):
    countRight = 0
    i = low + 1
    while i <= high:
        if st[i] < st[low]:
            countRight = countRight + 1
        i = i + 1

    return countRight

def findRank(st):
    ln = len(st)
    mul = fact(ln)
    rank = 1
    i = 0

    while i < ln:
        mul = mul / (ln - i)
        countRight = findSmallerInRight(st, i, ln - 1)

        rank = rank + countRight * mul
        i = i + 1

    return int(rank)


n=int(input())
l1=list(map(int, input().split()))
l2=list(map(int, input().split()))

s1=""
s2=""

for x in l1:
    s1=s1+str(x)

for x in l2:
    s2=s2+str(x)


print(abs(findRank(s1) - findRank(s2)))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
c1 = tuple(map(int, input().split()))
c2 = tuple(map(int, input().split()))
a = []
for i in range(1,n+1):
    a.append(i)
b = sorted(list(itertools.permutations(a)))
for i in range(len(b)):
    if b[i] == c1:
        d = i
    if b[i] == c2:
        e = i
print(abs(d-e))

Submission status: Accepted

Solution code:
def s_in():
    return input()

def n_in():
    return int(input())

def l_in():
    return list(map(int, input().split()))

class Interval():
    def __init__(self, li):
        self.li = li
        self.n = len(li)
        self.sum_li = [li[0]]
        for i in range(1, self.n):
            self.sum_li.append(self.sum_li[i-1] + li[i])

    def sum(self, a, b=None):
        if b is None:
            return self.sum(0, a)

        res = self.sum_li[min(self.n-1, b-1)]
        if a > 0:
            res -= self.sum_li[a-1]
        return res

N = n_in()
P = l_in()
Q = l_in()


kaijo = [1]

[kaijo.append((i+1)*kaijo[i]) for i in range(8)]


i = N-1
res = 0
lis = list(range(1, N+1))
for p in P[:N-1]:
    res += lis.index(p)*kaijo[i]
    lis.remove(p)
    i -= 1;

i = N-1
res2 = 0
lis = list(range(1, N+1))
for p in Q[:N-1]:
    res2 += lis.index(p)*kaijo[i]
    lis.remove(p)
    i -= 1;

print(abs(res-res2))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
lis = list(range(1,n+1))
count = 0
temp1 = 0
temp2 = 0
for v in itertools.permutations(lis):
    count += 1
    if list(v) == p:
        temp1 = count
    if list(v) == q:
        temp2 = count
print(abs(temp1-temp2))

Submission status: Accepted

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

import itertools
l = [i+1 for i in range(N)]

X = list(itertools.permutations(l, N))
print(abs(X.index(tuple(P))-X.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()))

k = list(itertools.permutations(p))

k.sort()

a = k.index(p)
b = k.index(q)

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

p_order = sorted(list(itertools.permutations(p)))
q_order = sorted(list(itertools.permutations(q)))

p_point = p_order.index(p)
q_point = q_order.index(q)

print(abs(p_point-q_point))

Submission status: Accepted

Solution code:
n = int(input())
p = input().split(" ")
q = input().split(" ")
for i in range(0, len(p)):
    p[i] = int(p[i])
for i in range(0, len(q)):
    q[i] = int(q[i])

def to_ordinal(num):
    global n
    nums = []
    all = 1
    for i in range(1, n+1):
        nums.append(i)
        all *= i
    
    result = 0
    for i in range(0, n):
        result += nums.index(num[i]) * all / (n-i)
        all /= n-i
        nums.remove(num[i])
    
    return int(result+1)

print(abs(to_ordinal(p) - to_ordinal(q)))

Submission status: Accepted

Solution code:
#import sys
MOD = 10 ** 9 + 7
#input = sys.stdin.readline
import math

import itertools

#import bisect

def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def kingaku(a,b,n):
    keta=len(str(n))
    return a*n+b*keta

def my_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default


#    h,w,a,b = map(int, input().split())
#    c = [[0 for j in range(n)] for i in range(n)]
def main():
    n=int(input())
    p=list(map(int,input().split()))
    q = list(map(int, input().split()))
    pn=0
    qn=0
    nn1 = [i+1 for i in range(n)]
    nn2 = [i + 1 for i in range(n)]
#    print(nn1)
    for i in range(n):
        pn+=(nn1.index(p[i]))*math.factorial(n-i-1)
        nn1.remove(p[i])
    for i in range(n):
        qn += (nn2.index(q[i])) * math.factorial(n - i - 1)
        nn2.remove(q[i])
#    print(pn,qn)
    print(abs(pn-qn))




if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import math
import sys

import itertools

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

#print (N,P,Q)
s = ""
for i in range(1,N+1):
    s=s + str(i)
# print(s)

iq= -1
ip = -1
i = 0 
for x in itertools.permutations(s):
    #print(x)
    s = ''.join(x)
    if P == s:
        ip = i
        if iq != -1:
            print(abs(ip -iq))
            exit(0)
    if Q == s:
        iq = i
        if ip != -1:
            print(abs(ip -iq))
            exit(0)
    i = i + 1    

exit(0)

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines


# mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
#import numpy as np
import math

def main():
	n=int(input())
	p=list(map(int,input().split()))
	q=list(map(int,input().split()))
	
	pl=list(range(n+1))
	pl.pop(0)
	ql=list(range(n+1))
	ql.pop(0)
	
	pp=0
	qq=0
	
	for i in range(n):
		ix=pl.index(p[i])
		pp+=ix*math.factorial(n-i-1)
		pl.remove(p[i])
	
	for i in range(n):
		ix=ql.index(q[i])
		qq+=ix*math.factorial(n-i-1)
		ql.remove(q[i])
	
	print(abs(pp-qq))
	
	
	
	



	
	
if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))

def saiki(lis,n,order):
    #print(order)
    if n==N:
        return order
    else:
        temp=0
        for item in lis[1:]:
            if lis[0]>item:
                temp+=1
        return saiki(lis[1:],n+1,order+temp*num[n]/len(lis))

num=[]
temp=1
for i in range(N):
    temp*=(i+1)
    num.append(temp)
num=num[::-1]

#print(num)

p=saiki(P,0,0)
q=saiki(Q,0,0)

print(abs(int(p-q)))

Submission status: Accepted

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

fact = {0: 1}
for i in range(1, n):
  fact[i] = fact[i-1] * i

num_list = [ i+1 for i in range(n) ]
p_order = 0
for i, p_i in enumerate(p):
  p_order += num_list.index(p_i) * fact[n - i - 1]
  num_list.remove(p_i)

num_list = [ i+1 for i in range(10) ]
q_order = 0
for i, q_i in enumerate(q):
  q_order += num_list.index(q_i) * fact[n - i - 1]
  num_list.remove(q_i)

print(abs(p_order - q_order))

Submission status: Accepted

Solution code:
from itertools import permutations

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

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

a, b, cnt = 0, 0, 1
for p in permutations(li, N):
  if list(p) == P:
    a = cnt
  if list(p) == Q:
    b = cnt
  cnt += 1
  
print(abs(a-b))

Submission status: Accepted

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

import itertools as it

############### TESTCASE ###############
test = ""
#test = \
"""
8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1
ans 17517
"""
########################################
test = list(reversed(test.strip().splitlines()))
if test:
    def input2():
        return test.pop()
else:
    def input2():
        return input()
################# MAIN ################# 

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

perm = tuple(it.permutations(range(1, n+1)))
ans = abs(perm.index(p) - perm.index(q))
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import itertools

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

s = set(range(1,n+1))

t = list(itertools.permutations(s, n))
a = t.index(P) + 1
b = t.index(Q) + 1
print((abs(a-b)))

Submission status: Accepted

Solution code:
from itertools import permutations

n = int(input())
s = tuple(map(int,input().split()))
t = tuple(map(int,input().split()))

a = list(permutations(list(range(1,n+1)),n))
a.sort()
for i in range(len(a)):
    if a[i] == s:
        p = i
    if a[i] == t:
        q = i
    
print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
p1 = 0
q1 = 0
count = 1
for i in itertools.permutations(range(1, n+1)):
    if p == i:
        p1 = count
    if q == i:
        q1 = count
    count += 1
print(abs(p1-q1))

Submission status: Accepted

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

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

def idx(lst):
  ans=0
  res = list(range(1,N+1))
  for i in range(N):
    #print(res)
    order = res.index(lst[i])
    #print(order)
    ans += fact(len(res)-1)*order
    #print(ans)
    res.remove(lst[i])
    #print(ans)
  return ans

#print(idx(P))
print(abs(idx(P)-idx(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
ans_q = 0
memo_p = [0]*n
memo_q = [0]*n
for i in range(n):
    ans_p += (p[i] - 1 - sum(memo_p[:p[i]-1])) * math.factorial(n - i - 1)
    memo_p[p[i] - 1] = 1
    ans_q += (q[i] - 1 - sum(memo_q[:q[i]-1])) * math.factorial(n - i - 1)
    memo_q[q[i] - 1] = 1
ans = abs(ans_p - ans_q)
print(ans)

Submission status: Accepted

Solution code:
import itertools as it

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

perms=list(it.permutations(range(1, N+1)))
a=perms.index(P)
b=perms.index(Q)

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
pi = 0
qi = 0
for i, item in enumerate(itertools.permutations(list(range(1,n+1)))):
    if item == p:
        pi = i
    if item == q:
        qi = i
print(abs(pi- qi))

Submission status: Accepted

Solution code:
import itertools
a = int(input())
b = list(map(int, input().split()))
c = list(map(int, input().split()))
r = list(itertools.permutations(range(1,a+1)))
k = []
for rr in r:
  k.append(list(rr))
#print(k)
p = k.index(b)
q = k.index(c)
print(max(p-q,q-p))

Submission status: Accepted

Solution code:
from math import factorial as f
n = int(input())
def sc(s, t, l):
  if t == 0:
    return 0
  i = s[0]
  for j in range(i+1, n+1):
    l[j] += 1
  return f(t-1)*(i-1-l[i]) + sc(s[1:], t-1, l)
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
pc = sc(P, n, [0 for _ in range(n+1)])
qc = sc(Q, n, [0 for _ in range(n+1)])
print(abs(qc-pc))

Submission status: Accepted

Solution code:
import itertools
import math

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

n_list = [i for i in range(1, n + 1)]
perms = itertools.permutations(n_list, n)
i = 1
for perm in perms:
    if list(perm) == p:
        a = i
    if list(perm) == q:
        b = i
    i += 1
print(abs(a - b))

Submission status: Accepted

Solution code:
#K, X = map(int, input().split())
# T = input()
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
p = [1 for _ in range(N)]
q = [1 for _ in range(N)]


def kaizyo(n):
    if n == 0:
        ans = 1
    else:
        ans = 1
    for i in range(1, n+1):
        ans *= i
    return ans

ansA = 0
ansB = 0
for i in range(N-1):
    p[P[i]-1] = 0
    q[Q[i]-1] = 0
    ansA += sum(p[:P[i]-1]) * kaizyo(N-1-i)
    ansB += sum(q[:Q[i]-1]) * kaizyo(N-1-i)

#print(ansA,ansB)
print(abs(ansA-ansB))

Submission status: Accepted

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

import itertools
for i,A in enumerate(itertools.permutations( [i for i in range(1,N+1)] )):
  if A==P:
    a=i+1
  if A==Q:
    b=i+1
print(abs(b-a))

Submission status: Accepted

Solution code:
import sys
import itertools

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

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

    jun_lis = list(itertools.permutations(kai))

    P_point = jun_lis.index(P)
    Q_point = jun_lis.index(Q)
    print(abs(P_point - Q_point))

main()

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
n_ = list(range(1, N + 1))
perm = list(itertools.permutations(n_))
print(abs(perm.index(P) - perm.index(Q)))

Submission status: Accepted

Solution code:
import itertools

N = int(input())

permu = [i+1 for i in range(N)]
s = 0
flag = False

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

if P==Q:
    print(s)
else:
    for i, value in enumerate(itertools.permutations(permu)):

        if value == P or value == Q:
            # print(i)
            if flag:
                s -= i
                break
            else:
                s += i
                flag = True

    print(abs(s))

Submission status: Accepted

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


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

    all_pattern = list(itertools.permutations(range(1, N + 1)))
    p_index = all_pattern.index(P) + 1
    q_index = all_pattern.index(Q) + 1

    print(abs(p_index - q_index))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import math

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

P_list = []
Q_list = []
for i in range(n):
    P_list.append(i+1)
    Q_list.append(i+1)

count_p = 1
count_q = 1
for i in range(n):
    p = P[i]
    ind = P_list.index(p)
    count_p += ind * math.factorial(n-i-1)
    P_list.pop(ind)
    
    q = Q[i]
    ind = Q_list.index(q)
    count_q += ind * math.factorial(n-i-1)
    Q_list.pop(ind)

print(abs(count_p-count_q))

Submission status: Accepted

Solution code:
from itertools import permutations
n = int(input())
p = tuple(int(x) for x in input().split())
q = tuple(int(x) for x in input().split())
permuts = list(permutations(range(1,n+1)))
print(abs(permuts.index(p) - permuts.index(q)))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = tuple(list(map(int, input().split())))
q = tuple(list(map(int, input().split())))
counter = 0
a = 0
b = 0
for i in itertools.permutations(range(1, n+1)):
    counter += 1
    if p == i:
        a = counter
    if q == i:
        b = counter

print(abs(a - b))

Submission status: Accepted

Solution code:
from itertools import permutations

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

index = {}
i = 0
for l in permutations(list(map(str, range(1, N + 1)))):
    i += 1
    index[''.join(l)] = i
print(abs(index[P] - index[Q]))

Submission status: Accepted

Solution code:
import itertools

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

pi = itertools.permutations(sorted(p))
a = 0
for pi_p in pi:
    a += 1
    if tuple(p) == pi_p:
        break

qi = itertools.permutations(sorted(q))
b = 0
for qi_q in qi:
    b += 1
    if tuple(q) == qi_q:
        break

print(abs(a - b))

Submission status: Accepted

Solution code:
from itertools import permutations

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

# Get all permutations of [1, 2, 3]
p = list(permutations([x for x in range(1, N+1)]))

a = p.index(P)
b = p.index(Q)

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

Submission status: Accepted

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

def solve(N: int, P: "List[int]", Q: "List[int]"):
    if P == Q:
        print(0)
        return 
    all = list(itertools.permutations(list(range(1,N+1)))) 
    a = None
    b = None
    P = tuple(P)
    Q = tuple(Q)
    for i in range(len(all)):
        if all[i] == P:
            a = i
        elif all[i] == Q:
            b = i
    
    print(abs(a-b))

    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    P = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    Q = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, P, Q)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools

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

A = list(range(1, n+1))
A = list(itertools.permutations(A, n))
            
a = A.index(P)
b = A.index(Q)
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

N = int(raw_input())
P = tuple(raw_input().split())
Q = tuple(raw_input().split())

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


perm = itertools.permutations(N_list)
index = 1

for item in perm:
    if P == item:
        index_p = index
    if Q == item:
        index_q = index
    index = index + 1

ans = index_p - index_q
if index_p - index_q < 0:
    ans = (-1)*ans

print ans

Submission status: Accepted

Solution code:
import itertools

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


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


def solve(temp):
    index = 0
    for group in itertools.permutations(answer, N):
        if list(group) == temp:
            return index
        index += 1


answer = solve(P) - solve(Q)

print(max(answer, -answer))

Submission status: Accepted

Solution code:
from math import factorial
from itertools import permutations

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

cases = []
nums = [i for i in range(1,N+1)]
for prm in permutations(nums, N):
    cases.append(prm)
cases.sort()

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

Submission status: Accepted

Solution code:
import itertools
import numpy as np

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

R = [n for n in range(1, N+1)]
R_P = itertools.permutations(R)

a = 0
for i, temp in enumerate(R_P):
    if P == list(temp):
        a = i+1
    if Q == list(temp):
        b = i+1
ans = np.abs(a-b)

print(ans)

Submission status: Accepted

Solution code:
import itertools

n = int(input())

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

p_s = tuple(p)
q_s = tuple(q)


base = list(itertools.permutations(set(p)))
a = base.index(p_s) + 1
b = base.index(q_s) + 1
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

from sys import stdin


def fetch_one_line():
    return stdin.readline().rstrip()


def fetch_int_input():
	return [int(s) for s in fetch_one_line().split()]
  
N = int(fetch_one_line())
P = fetch_int_input()
Q = fetch_int_input()

# l = ['a', 'b', 'c', 'd']
l = [i + 1 for i in range(N)]
n_list = itertools.permutations(l, len(l))

t_p = tuple(P)
t_q = tuple(Q)


for idx, n in enumerate(n_list):
	if n == t_p:
		p_idx = idx
	if n == t_q:
		q_idx = idx
    
print(abs(p_idx -  q_idx))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
all_n = []
for i in itertools.permutations(a):
    all_n.append(int("".join(map(str, i))))
all_n = sorted(all_n)
a = int("".join(map(str, a)))
b = int("".join(map(str, b)))
num_a = 0
num_b = 0
for i in range(len(all_n)):
    if all_n[i] == a:
        num_a = i + 1
    if all_n[i] == b:
        num_b = i + 1
print(abs(num_a - num_b))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
num = [1, 2, 3, 4, 5, 6, 7, 8]
num = num[:n]
list = list(itertools.permutations(num))
for i in range(len(list)):
    if ''.join(map(str, p)) == ''.join(map(str, list[i])):
        pi = i

for i in range(len(list)):
    if ''.join(map(str, q)) == ''.join(map(str, list[i])):
        qi = i

print(abs(pi-qi))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
Pn = tuple(map(int, input().split()))
Qn = tuple(map(int, input().split()))

all_pattern = itertools.permutations(range(1, N + 1), N)

result_map = {}
count = 0

for p in all_pattern:
    result_map[p] = count + 1
    count += 1
print(abs(result_map[Pn] - result_map[Qn]))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
S = sorted(list(itertools.permutations(P)))
S = [list(item) for item in S]
count = 0
nump = 0
numq = 0


for item in S:
    check = 0
    for i in range(N):
        if item[i] == P[i]:
            check+=1       
    if check == N:
        nump = count
        
    check = 0
    for i in range(N):
        if item[i] == Q[i]:
            check+=1
    if check == N:
        numq = count
    count += 1
    
print(abs(nump-numq))

Submission status: Accepted

Solution code:
from itertools import permutations


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

    d = [int(''.join(list(map(str, x)))) for x in permutations(range(1, N + 1), N)]

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
li=[]
import itertools
for i in itertools.permutations(p):
    li.append(list(i))
li.sort(reverse=False)
print(abs(li.index(p)-li.index(q)))

Submission status: Accepted

Solution code:
import itertools

n = [int(x + 1) for x in range(int(input()))]
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]

seq = list(itertools.permutations(n))

for i in range(len(seq)):
    if seq[i] == tuple(p):
        a = i
    if seq[i] == tuple(q):
        b = i

print(abs(a - b))

Submission status: Accepted

Solution code:
# coding: utf-8
import itertools

i = int(input())
p = tuple(int(i) for i in input().split())
q = tuple(int(i) for i in input().split())

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

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

Submission status: Accepted

Solution code:
import itertools
a=[]
n=int(input())
b=[]
for i in range(n):
    b.append(i+1)
for permutation in itertools.permutations(b):
    a.append(list(permutation))
c=a.index(list(map(int,input().split())))+1
d=a.index(list(map(int,input().split())))+1
print(abs(d-c))

Submission status: Accepted

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

for r in itertools.permutations(l, n):
    if P == list(r):
        a = i
    if Q == list(r):
        b = i
    i += 1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import bisect

N = int(input())
P = list(input().split())
Q = list(input().split())
p = ""
q = ""
for i in P:
    p += str(i)
for i in Q:
    q += str(i)
p = int(p)
q = int(q)

nums = [i for i in range(1, N+1)]
nums = list(itertools.permutations(nums))
lis = []
for num in nums:
    tmp = ""
    for i in num:
        tmp += str(i)
    lis.append(int(tmp))

#print(p, q)
print(abs(bisect.bisect_left(lis, p) - bisect.bisect_left(lis, q)))
#print(bisect.bisect_left(lis, q))

Submission status: Accepted

Solution code:
import itertools

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

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

junretu=list(itertools.permutations(l, N))
a=0
for i in junretu:
    a+=1
    if P==i:
        break
b=0
for i in junretu:
    b+=1
    if Q==i:
        break

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
N=int(input())
P=''.join(map(str,input().split()))
Q=''.join(map(str,input().split()))
x=sorted([''.join(map(str, s)) for s in itertools.permutations(range(1,N+1))])
print(abs(x.index(P)-x.index(Q)))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
N = [int(i) for i in range(1, n+1)]
l = []
for i in itertools.permutations(N):
    l.append(list(i))
#print(l)
p_num = l.index(p)
q_num = l.index(q)
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()))
rp = list(range(1,n+1))
rq = list(range(1,n+1))
import math
f = math.factorial(n)
ansp = 0
ansq = 0
for i in range(n):
  f //= (n-i)
  pi = rp.index(p[i])
  qi = rq.index(q[i])
  ansp += f*(pi)
  ansq += f*(qi)
  rp.remove(p[i])
  rq.remove(q[i])
print(abs(ansq-ansp))

Submission status: Accepted

Solution code:
import math

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


def solve(p, n):
  ans = 0
  l = list(range(1, n+1))
  for i in range(n):
    num = p[i]
    order = l.index(num) + 1
    l.remove(num)
    rest = len(l)

    ans += math.factorial(rest) * order

  return ans

print(abs(solve(p, n) - solve(q, n)))