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:
# -*- coding:utf-8 -*-
import copy

def solve():
    N = int(input())
    Ps = tuple(map(int, input().split()))
    Qs = tuple(map(int, input().split()))

    available_list = [i for i in range(1, N+1)]

    permutations = []  # 順列
    def _dfs(rest_list, p):
        if len(rest_list) == 0:
            permutations.append(tuple(p))
            return

        for i in range(1, N+1):
            if i in rest_list:
                tmp_rest_list = copy.deepcopy(rest_list)
                tmp_rest_list.remove(i)
                tmp_p = copy.deepcopy(p)
                tmp_p.append(i)
                _dfs(tmp_rest_list, tmp_p)


    _dfs(available_list, [])

    permutations.sort()

    for i, p in enumerate(permutations):
        if p == Ps:
            a = i+1
        if p == Qs:
            b = i+1

    print(abs(a-b))


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
import math
import string
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
import bisect

MOD = 10 ** 9 + 7
INF = float('inf')
input = lambda: sys.stdin.readline().strip()

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


def dictionary(info, n):
    if n == 1:
        return info
    MAX = max(info[0])
    info2 = []
    for i in range(MAX+1):
        for l in info:
            p = copy.deepcopy(l)
            p.insert(i, MAX+1)
            info2.append(p)
    return dictionary(info2, n - 1)


ans = sorted(dictionary([[1]], N))
print(abs(ans.index(P) - ans.index(Q)))

Submission status: Accepted

Solution code:
N = int(input())
p = ''.join(input().split())
q = ''.join(input().split())
found_p = found_q = False
import itertools
for i, cand in enumerate(itertools.permutations(range(1, N+1))):
  cand = ''.join([str(_) for _ in cand])
  if cand == p:
    a = i + 1
    found_p = True
  if cand == q:
    b = i + 1
    found_q = True
  if found_p and found_q:
    break
    
print(abs(a-b))

Submission status: Accepted

Solution code:

def main():
    
    n = int(input())

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

    head = [0,1,2,6,24,120,720,5040,40320]

    p_ = 0
    q_ = 0
    for i in range(n):
        #print(sorted(p_list[(i):]).index(p_list[i]))
        p_ += (head[(n)-(i+1)])* (sorted(p_list[(i):]).index(p_list[i]) )
        #print(p_)

        #print(sorted(q_list[(i):]).index(q_list[i]))
        q_ += (head[(n)-(i+1)])* (sorted(q_list[(i):]).index(q_list[i]) )
        #print(q_)

        #print(p_list)
        #print('###############')

    print(abs(p_-q_))


if __name__ == '__main__':
    main()

Submission status: Accepted

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

def solve(N: int, P: "List[int]", Q: "List[int]"):
    cnta = 0
    cntb = 0

    for i, x in enumerate(P):
        p_ = x-1
        for y in range(i):
            if P[y] < x : p_-=1
        cnta += p_ * math.factorial(N - 1 - i)
    for i, x in enumerate(Q):
        p_ = x-1
        for y in range(i):
            if Q[y] < x : p_-=1
        cntb += p_ * math.factorial(N - 1 - i)
    # print(cnta, cntb)
    print(abs(cnta-cntb))

    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:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
permutations_lis = itertools.permutations(range(1,n+1))# 全ての場合のリストを生成
dis_list = []
for i,case in enumerate(permutations_lis):
    if list(case) == p :
        a = i 
    if list(case) == q :
        b = i
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()))
x=[i+1 for i in range(n)]

x=list(itertools.permutations(x))
a=0
b=0

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

print(abs(a-b))

Submission status: Accepted

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

Submission status: Accepted

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

N = int(input())
permutations = list(itertools.permutations(list(range(1, N+1))))
p = tuple(map(int, input().split(' ')))
q = tuple(map(int, input().split(' ')))
order = [-1] * 2
for i in range(len(permutations)):
    if p == permutations[i]:
        order[0] = i
    if q == permutations[i]:
        order[1] = i
ans = abs(order[1] - order[0])
print(ans)

Submission status: Accepted

Solution code:
import fractions
import itertools

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

anslist=list(itertools.permutations(range(1,n+1)))
print(abs(anslist.index(p)-anslist.index(q)))

Submission status: Accepted

Solution code:
def dfs(res, chk):
    if len(res) == n:
        global idx
        global pi
        global qi
        idx += 1
        pb = all(res[i]+1 == p for i, p in enumerate(P))
        qb = all(res[i]+1 == q for i, q in enumerate(Q))
        if pb:
            pi = idx
        if qb:
            qi = idx
        return
    
    for i in range(n):
        if chk & (1 << i):
            continue
        else:
            dfs(res + [i], chk^(1 << i))

n = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
idx = 0
pi = qi = 0
perm = []
dfs([], 0)
print(abs(pi-qi))

Submission status: Accepted

Solution code:
import itertools

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

for idx, i in enumerate(itertools.permutations([i+1 for i in range(n)])):
    if i == p:
        a = idx
    
    if i == q:
        b = idx

print(abs(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(range(1,n+1))
a = 0
b = 0
x = itertools.permutations(l)
for i, e in enumerate(x,1):
    if p == e:
        a = i
    if q == e:
        b = i

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()))
nums = []
for i in range(1,n+1):
    nums.append(i)
cards = []
for card in itertools.permutations(nums):
    cards.append(list(card))

p_find = cards.index(p)
q_find = cards.index(q)
print(abs(p_find-q_find))

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

def load(vtype=int):
    return vtype(input().strip())

def load_list(seplator=" ", vtype=int):
    return [vtype(v) for v in input().strip().split(seplator)]

def exit():
    import sys
    sys.exit(0)

def kumiawase(li, used):
    if len(li) == len(used):
        return [[]]
    k = []
    for i in range(0, len(li)):
        if i in used:
            continue
        used.add(i)
        sub_list = kumiawase(li, used)
        for sub in sub_list:
            sub.append(li[i])
        k.extend(sub_list)
        used.discard(i)
    return k
        
n = load()
p = "".join(load_list(vtype=str))
q = "".join(load_list(vtype=str))

ks = kumiawase([i for i in range(n, 0, -1)], set())
ks = sorted(["".join([str(e) for e in k]) for k in ks])

a = ks.index(p) + 1
b = ks.index(q) + 1
print(abs(a-b))

Submission status: Accepted

Solution code:
# import math
# import bisect
# import heapq
# from copy import deepcopy
# from collections import deque
# from collections import Counter
# from itertools import accumulate
from itertools import permutations
# import numpy as np


# k,x = map(int, input().split())

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
m = [i + 1 for i in range(n)]
c = 0

for i in permutations(m):
    c += 1
    # print(i)
    if list(i) == p:
        a = c
    if list(i) == q:
        b = c

print(abs(a - b))

Submission status: Accepted

Solution code:
from sys import stdin
import math
import itertools

n = int(stdin.readline().rstrip())
p = [int(x) for x in stdin.readline().rstrip().split()]
q = [int(x) for x in stdin.readline().rstrip().split()]

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

l = itertools.permutations(nn, n)

pp = 0
qq = 0
for i in range(n):
    pp += p[i] * (10 ** (n - i - 1))
    qq += q[i] * (10 ** (n - i - 1))

a = 1
b = 1
ar = 0
br = 0
for v in l:
    vv = 0
    for i in range(n):
        vv += v[i] * (10 ** (n - i - 1))
    if pp == vv:
        ar = a
    else:
        a += 1
    if qq == vv:
        br = b
    else:
        b += 1
    
print(abs(ar - br))

Submission status: Accepted

Solution code:
import itertools

ii = lambda : int(input())
li = lambda : tuple(map(int,input().split()))

n = ii()
p = li()
q = li()

p_pos = q_pos = -1

for k,i in enumerate(itertools.permutations(range(1,n+1))):
    if(p_pos != -1) & (q_pos != -1):
        break
    if(p == i):
        p_pos = k
        
    if(q == i):
        q_pos = k
    
print(abs(p_pos-q_pos))

Submission status: Accepted

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

num = []
numset = []
for i in range(N):
    num.append(i + 1)
num = [str(_) for _ in num]
numset = list(itertools.permutations(num, N))
Pn = 1
Qn = 1
cnt = 1
for a in list(itertools.permutations(num, N)):
    if P == list(a):
        Pn = cnt
    if Q == list(a):
        Qn = cnt
    cnt += 1
print(abs(Pn-Qn))

Submission status: Accepted

Solution code:
import itertools

n = list(range(1, int(input()) + 1))
s1 = tuple(map(int, input().split()))
s2 = tuple(map(int, input().split()))
perm = list(itertools.permutations(n))
a = perm.index(s1)
b = perm.index(s2)

print(abs(a - b))

Submission status: Accepted

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

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

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

num_q = 1
for i in range(n):
    cnt = 0
    for j in range(i+1,n):
        if(q[i] > q[j]):
            cnt += 1
    #print(cnt)
    num_q += math.factorial(n-i-1)*cnt
    
#print(num_p)
#print(num_q)
print(abs(num_p-num_q))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
m = [i + 1 for i in range(n)]
c = 0
for i in itertools.permutations(m):
    c += 1
    if list(i) == p:
        a = c
    if list(i) == q:
        b = c
print(abs(a - b))

Submission status: Accepted

Solution code:

import bisect
from itertools import permutations


def submit():
    n = int(input())
    p = "".join(input().split())
    q = "".join(input().split())
    
    patterns = list(map(lambda x: "".join(x), permutations(map(str, range(1, n + 1)))))
    a = bisect.bisect_left(patterns, p)
    b = bisect.bisect_left(patterns, q)
    print(abs(a - b))


if __name__ == "__main__":
    submit()

Submission status: Accepted

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

a, b = 0, 0
perms = list(permutations(range(1, N + 1)))

for per in perms:
    if P == per:
        a = perms.index(per) + 1
    if Q == per:
        b = perms.index(per) + 1

print(abs(a - b))

Submission status: Accepted

Solution code:
import itertools

n = int(input())

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

# print(p_list, q_list)

p_i, q_i = -1, -1
for i, series in enumerate(itertools.permutations(range(1, n + 1))):
    # print(series)
    if p_list == series:
        # print('p')
        p_i = i
    if q_list == series:
        # print('q')
        q_i = i
    if p_i != -1 and q_i  != -1:
        break

# print(p_i, q_i)
print(abs(p_i - q_i))

Submission status: Accepted

Solution code:
n = int(input())
p = input().replace(" ", "")
q = input().replace(" ", "")
num_list = [0 for _ in range(n)]

def create(N, N_list, num, count):
    if count==num:
        return [N]
    result = []
    for i in range(1,num+1):
        if N_list[i-1]==0:
            next_N_list = N_list.copy()
            next_N_list[i-1] = 1
            result.extend(create(N*10+i, next_N_list, num, count+1))
    return result
dic = sorted(create(0, num_list, n, 0))
print(abs(dic.index(int(p))-dic.index(int(q))))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
lst_n = [i for i in range(1, n+1)]

lst_p = list(itertools.permutations(lst_n))
    
p = lst_p.index(tuple(map(int, input().split())))
q = lst_p.index(tuple(map(int, input().split())))
print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools

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

all_pattern = sorted(list(itertools.permutations(p)))
a, b = 0, 0
for i, pattern in enumerate(all_pattern):
    if list(pattern) == p:
        a = i
    if list(pattern) == q:
        b = i
print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations

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

a,b = 0, 0

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

print(abs(a-b))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))

from collections import deque
#階乗 kaijo
import math
kaijo_list = [math.factorial(i) for i in range(1,9)]
def calc_dict_order(int_list):
    ret = 0
    int_list=deque(int_list)
    base_dict = [i for i in range(1,n+1)]
    while int_list:
        x = int_list.popleft()
        rank_x = base_dict.index(x)
        del base_dict[rank_x]
        ret+=(rank_x*kaijo_list[len(base_dict)-1])
    return ret
print(abs(calc_dict_order(p)-calc_dict_order(q)))

Submission status: Accepted

Solution code:
def resolve():
    import itertools
    import math
    n = int(input())
    a = tuple(map(int, input().split()))
    b = tuple(map(int, input().split()))
    alist = list(itertools.permutations(sorted(a)))
    for i in range(math.factorial(n)):
        if alist[i] == a:
            numa = i+1
        if alist[i] ==b:
            numb = i+1
    print(abs(numa-numb))
resolve()

Submission status: Accepted

Solution code:
from itertools import permutations

n = int(input())
all_ = list(permutations([i+1 for i in range(n)], n))
l_p = tuple(map(int, input().split()))
l_q = tuple(map(int, input().split()))

res = abs(all_.index(l_p) - all_.index(l_q))
print(res)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from numpy import prod

n = int(input())

def solve(l:list):
  now = [i + 1 for i in range(n)]
  res = 0
  for i in range(n):
    res += now.index(l[i]) * prod([j+1 for j in range(len(now)-1)])
    now.remove(l[i])
  return res

l_p = list(map(int, input().split()))
l_q = list(map(int, input().split()))

print(int(abs(solve(l_p) - solve(l_q))))

Submission status: Accepted

Solution code:
import itertools

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

a,b = 0,0
for i,x in enumerate(itertools.permutations(range(1,n+1))):

    if list(x) == p:
        a = i
    if list(x) == q:
        b = i
        
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

for perm in itertools.permutations(range(1, N + 1), N):
    p = ""
    for per in perm:
        p += str(per)
    A.append(p)
A.sort()
print(abs(A.index(P) - A.index(Q)))

Submission status: Accepted

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

junretu = [i + 1 for i in range(N)]
cnt = 0
for i in itertools.permutations(junretu, N):
    cnt += 1
    if i == p:
        a = cnt
        #cnt += 1
    if i == q:
        b = cnt
        #cnt += 1
    #cnt += 1
print(abs(a - b))

Submission status: Accepted

Solution code:
from itertools import permutations
N = int(input())
P, Q = input().replace(' ', ''), input().replace(' ', '')
a = b = x = 0
for d in permutations(''.join(map(str, range(1, N+1))), N):
  x += 1
  s = ''.join(d)
  if s == P:
    a = x
  if s == Q:
    b = x
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 = [i for i in range(1,N+1)]
count = 1
for i in itertools.permutations(A):
    flg = True
    for k in range(N):
        if i[k] != P[k]:
            flg = False
            break
    if flg:
        a = count
    flg = True
    for k in range(N):
        if i[k] != Q[k]:
            flg = False
            break
    if flg:
        b = count
    count += 1
print(abs(a-b))

Submission status: Accepted

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

P = tuple(P)
Q = tuple(Q)
dlist = range(1, N+1)
permlist = list(itertools.permutations(dlist))

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

Submission status: Accepted

Solution code:
import math
n=int(input())
suretu1=list(map(int,input().split()))
suretu2=list(map(int,input().split()))
zyun1=0
zyun2=0
count=0
for i in range(n):
    n_suretu1=sorted(suretu1)
    for j in range(len(suretu1)):
        if suretu1[0]==n_suretu1[j]:
            count=j+1
    zyun1+=math.factorial(n-i-1)*(count-1)
    del suretu1[0]
for i in range(n):
    n_suretu2=sorted(suretu2)
    for j in range(len(suretu2)):
        if suretu2[0]==n_suretu2[j]:
            count=j+1
    zyun2+=math.factorial(n-i-1)*(count-1)
    del suretu2[0]
print(abs(zyun1-zyun2))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
P = input().split()
numbers = list(itertools.permutations(P))
P = ''.join(P)
Q = input()
Q = Q.replace(' ', '')

numbers_str = []
for num in numbers:
    numbers_str.append(''.join(num))
numbers_str.sort()
print(abs(numbers_str.index(P)-numbers_str.index(Q)))

Submission status: Accepted

Solution code:
from itertools import permutations

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

    perm_p = sorted(permutations(p))
    perm_q = sorted(permutations(q))

    a, b = 0, 0
    for i, _p in enumerate(perm_p):
        if p == _p:
            a = i
            break
    
    for i, _q in enumerate(perm_q):
        if q == _q:
            b = i
            break
    
    print(abs(a - b))
    

if __name__ == "__main__":
    solve()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
pp = "".join([str(i) for i in p])
q = list(map(int, input().split()))
qq = "".join([str(i) for i in q])
x = [i+1 for i in range(n)]
z = []
for v in itertools.permutations(x):
	y = "".join([str(i) for i in v])
	z.append(y)
a = z.index(pp)
b = z.index(qq)
print (abs(a-b))

Submission status: Accepted

Solution code:
a = list(map(int,input().split()))
a_1 = list(map(int,input().split()))
a_2 = list(map(int,input().split()))

def kaijo(a) :
    k = 1
    for i in range(1,a+1) :
        k = k * i
    return k

def zyunretsu(N) :
    len_N = len(N) - 1
    c = 1
    for i in range(0,len(N)) :
        if len_N == 0 :
            break
        a = N[0]
        N_C = sorted(N)
        b = N_C.index(a)
        c = c + kaijo(len_N) * b
        N.remove(a)
        len_N = len_N - 1
    return c

print(abs(zyunretsu(a_1)-zyunretsu(a_2)))

Submission status: Accepted

Solution code:
from itertools import permutations

N = int(input())
P = list(map(str,input().split()))
Q = list(map(str,input().split()))
P = "".join(P)
Q = "".join(Q)
l = []
ll = []
for i in range(1,N + 1):
    l.append(i)

comb = list(permutations(l,N))

for i in range(len(comb)):
    a = list(map(str,comb[i]))
    ll.append("".join(a))

P_ind = ll.index(P)
Q_ind = ll.index(Q)
print(abs(P_ind - Q_ind))

Submission status: Accepted

Solution code:
from itertools import permutations

n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
if p == q:
    print(0)
    exit()
base = sorted(p)
pi = 0
qi = 0
for i, v in enumerate(permutations(base, n)):
    if p == v:
        pi = i + 1
    elif q == v:
        qi = i + 1
        
    if pi * qi != 0:
        break
# print(f"{pi} {qi}")
print(abs(pi-qi))

Submission status: Accepted

Solution code:
import itertools

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

seq = tuple([i+1 for i in range(n)])
seqlist = list(itertools.permutations(seq))
pint = 0
qint = 0

for i, hoge in enumerate(seqlist):
  if hoge == p:
    pint = i
  if hoge == q:
    qint = i

print(abs(pint - qint))

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


def read_values():
    return map(int, input().split())


def read_list():
    return list(read_values())


def main():
    import itertools

    N = int(input())
    P = tuple(read_list())
    Q = tuple(read_list())

    T = list(itertools.permutations([i for i in range(1, N + 1)]))
    print(abs(T.index(Q) - T.index(P)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import itertools
n = int(input())
A  = tuple(map(int,input().split()))
B  = tuple(map(int,input().split()))
Z = list(itertools.permutations(range(1,n+1)))
a = 0
b = 0
for i,z in enumerate(Z):
  #print(z,A)
  if(z == A):
    a = i+1
  if(z == B):
    b = i+1
print(abs(a-b))

Submission status: Accepted

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

l = list(range(1,n+1))
num = 0
for i in range(n):
     a = l.index(int(p[i]))
     l.remove(int(p[i]))

     num += a * math.factorial(n-i-1)

l1 = list(range(1,n+1))
num1 = 0
for i in range(n):
     a = l1.index(int(q[i]))
     l1.remove(int(q[i]))
     num1 += a * math.factorial(n-i-1)

print(abs(num -num1))

Submission status: Accepted

Solution code:
import itertools

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

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

a = 0
b = 0
for i, p in enumerate(permlist):
	if P == p:
		a = i
	if Q == p:
		b = i

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()))
l = []
for i in range(N):
    l.append(i + 1)

# 重複なしのあらゆる並び(itertools.permutations)
l = list(map(list, itertools.permutations(l)))
print(abs(l.index(P) - l.index(Q)))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
l = []
c = []
ls = []
for i in range(N):
    l.append(i + 1)
    c.append(0)

# 重複なしのあらゆる並び
l = list(map(list, itertools.permutations(l)))
print(abs(l.index(P) - l.index(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()))
PER = list(itertools.permutations([i for i in range(1, N+1)], N))
print(abs(PER.index(P)-PER.index(Q)))

Submission status: Accepted

Solution code:
import itertools

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    l = [i for i in range(1, N+1)]
    l = list(itertools.permutations(l))
    
    a = 0
    b = 0
    for k, v in enumerate(l):
        v = list(v)
        if v == A:
            a = k+1
        if v == B:
            b = k+1
    
    return abs(a-b)

print(solve())

Submission status: Accepted

Solution code:
import itertools

def solve():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    l = [i for i in range(1, N+1)]
    l = list(itertools.permutations(l))
    
    a = 0
    for k, v in enumerate(l):
        if A == list(v):
            a = k+1
        
    b = 0
    for k, v in enumerate(l):
        if B == list(v):
            b = k+1
    return abs(a-b)

print(solve())

Submission status: Accepted

Solution code:
from itertools import permutations


n = int(input())
A = [i for i in range(1, n+1)]
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
if P == Q:
    print(0)
    exit()
cnt = 0
for v in permutations(A, n):
    cnt += 1
    if v == P:
        a = cnt
    elif v == Q:
        b = cnt
print(abs(a - b))

Submission status: Accepted

Solution code:
def kaijo(num):
    a = 1
    for i in range(num, 1, -1):
        a *= i
    return a

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

p_len = 0
for i in range(n - 1):
    a = p[i]
    p_len += (len(list(filter(lambda x: x < a, p[i:]))) - 1) * kaijo(n - i - 1)

for i in range(n - 1):
    b = q[i]
    p_len -= (len(list(filter(lambda x: x < b, q[i:]))) - 1) * kaijo(n - i - 1)

print(abs(p_len))

Submission status: Accepted

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

from itertools import permutations as pe
arr=[list(x) for x in pe(range(1,n+1))]

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()))
  
  
def factorial(n):
  if n==1:
    return 1
  else:
    return n * factorial(n-1)
  
num_p=0
num_q=0
for i in range(n-1):
  sort_p = sorted(p[i:],reverse=True)
  index_p = sort_p.index(p[i])
  mp=n-(index_p+1)
  num_p += mp*factorial(n-(i+1))
  
  
  sort_q = sorted(q[i:],reverse=True)
  index_q = sort_q.index(q[i])
  mq = n-(index_q+1)
  num_q += mq*factorial(n-(i+1))
  
print(abs(num_p-num_q))

Submission status: Accepted

Solution code:
from math import factorial
n=int(input())
*l1,=map(int,input().split())
*l2,=map(int,input().split())
ansl=[]
for l in [l1,l2]:
  l_ref = list(range(1,n+1))
  ans = 0
  m = n-1
  for i in l:
    ans += factorial(m) * l_ref.index(i)
    l_ref.remove(i)
    m-=1
  ansl.append(ans)
print(abs(ansl[1]-ansl[0]))

Submission status: Accepted

Solution code:
input()
a=list(map(int,input().split()))
b=list(map(int,input().split()))
fa=lambda n:1 if n==0 else n*fa(n-1)
in1=1
in2=1
li=[i+1 for i in range(len(a))]
li2=[i+1 for i in range(len(a))]
for i in a:
  in1+=fa(len(li)-1)*li.index(i)
  del li[li.index(i)]
for i in b:
  in2+=fa(len(li2)-1)*li2.index(i)
  del li2[li2.index(i)]
print(abs(in1-in2))

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

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

a = 0
b = 0

for i, v in enumerate(X):
    if v == P:
        a = i
    if v == Q:
        b = i

print(abs(a-b))

Submission status: Accepted

Solution code:
N = int(input())
P = "".join(input().split())
Q = "".join(input().split())
l_p = []

def f_perm(bit, s_p):
  if len(s_p) == N:
    l_p.append(s_p)
    return
  for i in range(N):
    if 1 << i & bit != 0:
      continue
    f_perm(bit | 1 << i, s_p + str(i + 1))

f_perm(0, "")    
    
print(abs(l_p.index(P) - l_p.index(Q)))

Submission status: Accepted

Solution code:
import itertools
N=int(input())
a="".join(input().split())
b="".join(input().split())
li=[]
for k in itertools.permutations([str(i+1) for i in range(N)],N):
    li.append("".join(k))
li.sort()
print(abs(li.index(a)-li.index(b)))

Submission status: Accepted

Solution code:
import sys

import math
import itertools

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n = ni()
p = na()
q = na()
l = list(itertools.permutations(list(range(1, n+1))))
print(abs(l.index(tuple(p)) - l.index(tuple(q))))

Submission status: Accepted

Solution code:
import sys
from itertools import permutations 
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

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

p = "".join(P)
q = "".join(Q)

arr = []
perm = permutations(sorted(Q))
for x in perm:
   arr.append("".join(str(y) for y in x))

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

Submission status: Accepted

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

a = 0
b = 0
for i,now in enumerate(itertools.permutations(range(n))):
  if (now == p):
    a = i
  if (now == q):
    b = i
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

perm = list(itertools.permutations(range(N),N))

a = sum([1 if list(p)<=P else 0 for p in perm])
b = sum([1 if list(p)<=Q else 0 for p in perm])

print(abs(a-b))

Submission status: Accepted

Solution code:
#150_C
from itertools import permutations

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

for i,x in enumerate(permutations(range(1,n+1))):
    if p==x:a=i
    if q==x:b=i
print(abs(a-b))