Problem:


Score : 300 points

Problem Statement

We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).

There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.

Notes

For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.

Sample Input 2

8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0



Sample input:
3
1 3 2
3 1 2


Sample output:
3

Submission status: Accepted

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

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

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

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

Submission status: Accepted

Solution code:
import math

N = int(input())
Pi = list(map(int,input().split()))
Qi = list(map(int,input().split()))

a = 0
b = 0

numcheck = [1 for i in range(N)]
numcheck[Pi[0]-1] = 0
a = math.factorial(N-1)*(Pi[0]-1) 
for n in range(1,N):
  num = Pi[n]
  numcheck[num-1] = 0
  a = a + math.factorial(N-1-n)*sum(numcheck[:num])
a = a + 1

numcheck = [1 for i in range(N)]
numcheck[Qi[0]-1] = 0
b = math.factorial(N-1)*(Qi[0]-1) 
for n in range(1,N):
  num = Qi[n]
  numcheck[num-1] = 0
  b = b + math.factorial(N-1-n)*sum(numcheck[:num])
b = b + 1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
inlst = []

for _ in range(2):
    inlst.append(list(map(int, input().split())))

lst = list(range(1, N + 1))
per = list(itertools.permutations(lst))

ab = []
for i, v in enumerate(inlst):
    ab.append(per.index(tuple(v)) + 1)

a, b = ab
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
ss = []
for s in permutations(range(1, n + 1)):
    ss.append(s)
ss = sorted(ss)
for k, s in enumerate(ss):
    if list(s) == p:
        a = k
    if list(s) == q:
        b = k

print(abs(a - b))

Submission status: Accepted

Solution code:
N = int(input())

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

from itertools import permutations
Perm = permutations(range(1,N+1),N)
a = 0
b = 0
for i,p in enumerate(Perm):
    if P == p: a = i
    if Q == p: b = i
print(abs(a-b))

Submission status: Accepted

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

from itertools import permutations
asc = list(range(1, N+1))
#print(len(list(permutations(asc))))
xp, xq = -1, -1
for i, arr in enumerate(permutations(asc)):
  #print(i, arr)
  if arr == P:
    xp = i
  if arr == Q:
    xq = i
  if xp > -1 and xq > -1:
    break
ans = abs(xp - xq)
print(ans)

Submission status: Accepted

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

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

nums = list(itertools.permutations(List))

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

print(abs(a-b))

Submission status: Accepted

Solution code:
n = int(input())
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
l = tuple(x+1 for x in range(n))
c,d = 0,0
cnt = 0
from itertools import permutations
for k in permutations(l):
    cnt += 1
    if a ==k:
        c = cnt
    if b ==k:
        d = cnt
print(abs(c-d))

Submission status: Accepted

Solution code:
n = int(input())
a = tuple(map(int,input().split()))
b = tuple(map(int,input().split()))
l = tuple(x+1 for x in range(n))
#print(a,b,l)
c,d = 0,0
cnt = 0
from itertools import permutations
for k in permutations(l):
    #print(k)
    cnt += 1
    if a ==k:
        c = cnt
    if b ==k:
        d = cnt
print(abs(c-d))

Submission status: Accepted

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

import itertools as it
pe=list(it.permutations(range(n),n))

x,y=0,0
for ind,i in enumerate(pe):
    if i==a:
        x=ind
    if i==b:
        y=ind
print(abs(x-y))

Submission status: Accepted

Solution code:
import itertools

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

cnt = 0
a, b = 0, 0
perms = itertools.permutations(range(1, N+1))
for perm in perms:
  cnt += 1
  # P
  is_P = True
  for i in range(N):
    if perm[i] != P[i]:
      is_P = False
      break
  if is_P:
    a = cnt
  # Q
  is_Q = True
  for i in range(N):
    if perm[i] != Q[i]:
      is_Q = False
      break
  if is_Q:
    b = cnt
print(abs(a-b))

Submission status: Accepted

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

def solve(N: int, P: "List[int]", Q: "List[int]"):
    a = 0
    b = 0
    for i, v in enumerate(itertools.permutations(range(1, N+1))):
        flagp = True
        flagq = True
        for j in range(N):
            if v[j] != P[j]:
                flagp = False
            if v[j] != Q[j]:
                flagq = False
        if flagp:
            a = i+1
        if flagq:
            b = i+1
    print(abs(b-a))
    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 math
import itertools
N=int(input())
Plist=tuple(map(str,input().split()))
Qlist=tuple(map(str,input().split()))

#number=math.fractorial(N)
s_number=""

for i in range(1,N+1):
    s_number+=str(i)
    
#print(s_number)

#Plistを調べる
j=0


for i in itertools.permutations(s_number):
    #print(i)
    #print(j)
    
    if i==Plist:
        a=j
    j+=1
    
#Qlistを調べる    
j=0

for i in itertools.permutations(s_number):
    #print(i)
    #print(j)
    
    if i==Qlist:
        b=j
    j+=1
    
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

n = int(input())

array = [i for i in range(1, n + 1)]
gen_array = itertools.permutations(array, n)

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

idx = 1
for lis in gen_array:
    if list(lis) == a:
        num_a = idx
    if list(lis) == b:
        num_b = idx
    idx += 1

print(abs(num_a - num_b))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
ps = list(map(int, input().strip().split()))
qs = list(map(int, input().strip().split()))

perms = itertools.permutations(range(1, n + 1))

for idx, perm in enumerate(perms):
    perm_l = list(perm)
    if ps == perm_l:
        a = idx + 1
    if qs == perm_l:
        b = idx + 1

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

p = sorted(permutations(range(1, N + 1), N))
print(abs(p.index(Q) - p.index(P)))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
for i, a in enumerate(itertools.permutations(range(1, 1+N))):
    if a == P:
        p = i
    if a == Q:
        q = i
        
print(abs(p-q))

Submission status: Accepted

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

permutations = list(itertools.permutations(range(1, N+1)))
p = permutations.index(P)
q = permutations.index(Q)

ans = abs(p - q)
print(ans)

Submission status: Accepted

Solution code:
import itertools

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

# print(P,Q)
perm = list(itertools.permutations(range(1,N+1)))
# print(perm)
a=perm.index(tuple(P))+1
# print(perm.index(tuple(P)))
b=perm.index(tuple(Q))+1
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
l = []
p_num = 0
q_num = 0
n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
for i in range(1,n+1):
    l.append(i)
cnt = 0
for i in itertools.permutations(l,n):
    cnt += 1
    if i == p:
        p_num = cnt
    if i == q:
        q_num = cnt
        
print(abs(p_num - q_num))

Submission status: Accepted

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

a=set()
b=set()

ans=0

for i in range(n):
    ans+=(p[i] - len([j for j in a if j < p[i]])) * math.factorial(n-i-1)
    a.add(p[i])
    ans-=(q[i] - len([j for j in b if j < q[i]])) * math.factorial(n-i-1)
    b.add(q[i])

print(abs(ans))

Submission status: Accepted

Solution code:
import itertools

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

list_range = list(range(1,n+1))
pattern_list = list(itertools.permutations(list_range, n))
pattern_list.sort()
ans = [0] * 2
for i in range(len(pattern_list)):
  if p == q:
    break
  elif p == list(pattern_list[i]):
    ans[0] = i + 1
  elif q == list(pattern_list[i]):
    ans[1] = i + 1
print(abs(ans[0] - ans[1]))

Submission status: Accepted

Solution code:
import itertools

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

list_perm = list(itertools.permutations([i+1 for i in range(N)]))

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

Submission status: Accepted

Solution code:
import itertools

## N
n_int = int(input())

## P
p_int_list = list(map(int, input().split()))
## 結合して1つの数値にする。
p_int = int("".join(map(str, p_int_list)))

## Q
q_int_list = list(map(int, input().split()))
## 結合して1つの数値にする。
q_int = int("".join(map(str, q_int_list)))

## 総数リスト
n_list = []
for i in range(n_int):
    n_list.append(i + 1)

p_cnt = 0
q_cnt = 0
## 順列を生成してループで列挙
for perm_arr in itertools.permutations(n_list, n_int):

    perm_int = int("".join(map(str, perm_arr)))

    ## 入力数値以下の場合は、カウント 1加算
    if perm_int <= p_int :
        p_cnt += 1

    if perm_int <= q_int :
        q_cnt += 1

    ## 全ての入力数値を超えた場合は、break
    if  perm_int > p_int \
    and perm_int > q_int :
        break

print(abs(p_cnt - q_cnt))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
pis = tuple([int(pi) for pi in input().split()])
qis = tuple([int(qi) for qi in input().split()])
perms = list(itertools.permutations(range(1,n+1)))

pn = -1
qn = -1
for p in perms:
  if pis == p:
    pn = perms.index(pis)
    
  if qis == p:
    qn = perms.index(qis)
    
  if pn > -1 and qn > -1:
    break
print(abs(pn - qn))

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
cp = 0
cq = 0
def kai(a):
    if a <= 1:
        return 1
    else:
        return a*kai(a-1)
for i in range(n):
    cp += (p[i]-1)*kai(n-i-1)
    cq += (q[i]-1)*kai(n-i-1)
    for j in range(n):
        if p[j] > p[i]:
            p[j] -= 1
        if q[j] > q[i]:
            q[j] -= 1
print(abs(cp-cq))

Submission status: Accepted

Solution code:
N = int(input())
P = input().replace(" ","")
Q = input().replace(" ","")

def add_up(string, left):
  string_set = set()
  if len(left) == 0:
    return {string}
  
  for number in left:
    string_set |= add_up(string+str(number), left-{number})
  return string_set

l = sorted(list(add_up("",set([i+1 for i in range(N)]))))
print(abs(l.index(Q)-l.index(P)))

Submission status: Accepted

Solution code:
import math

N = int(input())
P = input().split(' ')
sorted_P = sorted(P)
P_num = 0
Q = input().split(' ')
sorted_Q = sorted(Q)
Q_num = 0
for i in range(len(P) - 1):
    P_num += sorted_P.index(P[i]) * math.factorial(N - i - 1)
    sorted_P.pop(sorted_P.index(P[i]))
for j in range(len(Q) - 1):
    Q_num += sorted_Q.index(Q[j]) * math.factorial(N - j - 1)
    sorted_Q.pop(sorted_Q.index(Q[j]))
print(abs(P_num - Q_num))

Submission status: Accepted

Solution code:
import itertools

n=int(input())
p=list(input().split())
q=list(input().split())
l=[]
for v in itertools.permutations(p,n):
    l.append(list(v))
    
l=sorted(l)
p_val=0
q_val=0
m=0
for i in l:
    if i==p:
        p_val=m
    if i==q:
        q_val=m
    m+=1

print(abs(p_val-q_val))

Submission status: Accepted

Solution code:
from itertools import permutations
N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
i = a = b = 0
for x in permutations(range(1, N+1), N):
  i += 1
  if x == P:
    a = i
  if x == 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()))
v = P[:]
v.sort()
p = tuple(P)
q = tuple(Q)
ans_a = 0
ans_b = 0
if p == q:
    print(0)
else:
    for i, l in enumerate(itertools.permutations(v)):
        if p == l:
            ans_a = i + 1
        elif q == l:
            ans_b = i + 1
    print(abs(ans_a - ans_b))

Submission status: Accepted

Solution code:
from __future__ import print_function

import sys

import re
import array
import copy
import functools
import operator

import math
import string
import fractions
from fractions import Fraction
from fractions import gcd
# fractions.gcd() を用いること
# math.log2()はatcoderでは対応していない．留意せよ．

import collections
import itertools
import bisect

import random
import time

import heapq
from heapq import heappush
from heapq import heappop
from heapq import heappushpop
from heapq import heapify
from heapq import heapreplace
from queue import PriorityQueue as pq
from queue import Queue

from itertools import accumulate

from collections import deque
from collections import Counter

from operator import mul
from functools import reduce

input = sys.stdin.readline


def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)
    return


def lcm(n, m):
    return int(n * m / gcd(n, m))


def coprimize(p, q):
    common = fractions.gcd(p, q)
    return (p // common, q // common)


def combinations_count(n, r):
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom


def main():
    n = int(input().strip())
    a = tuple(map(int, input().strip().split()))
    b = tuple(map(int, input().strip().split()))
    l = tuple([i+1 for i in range(n)])

    n_a = 0
    n_b = 0
    for (seq, i) in zip((itertools.permutations(l)), [i for i in range(math.factorial(n))]):
        if seq == a:
            n_a = i
        if seq == b:
            n_b = i
    print(abs(n_a - n_b))


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

if P == Q:
    print(0)
else:
    l = []
    for i in range(1, N+1):
        l.append(i)

    t = tuple(l)
    p = 0
    q = 0
    for i, v in enumerate(itertools.permutations(t)):
        if P == v:
            p = i+1
        elif Q == v:
            q = i+1
    print(abs(p - q))

Submission status: Accepted

Solution code:
#16　AtCoder Beginner Contest 150 C - Count Order
import itertools
n = int(input())
p = tuple(map(int, input().split()))
q = tuple(map(int, input().split()))
ans = 0
j = 0
for i in itertools.permutations(range(1, n+1)):
    j += 1
    if p == i: ans += j
    if q == i: ans -= j
print(abs(ans))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]
p1 = ""
for i in p:
    p1 += str(i)

q1 = ""
for i in q:
    q1 += str(i)


a = list(map(list, itertools.permutations(p, n)))
a.sort()
b = []

for i in a:
    g = ""
    for j in i:
        g += str(j)
    b.append(g)

print(abs((b.index(p1)+1) - (b.index(q1)+1)))

Submission status: Accepted

Solution code:
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
from itertools import *
cnt=0
for i in list(permutations(range(1,n+1))):
    if list(i) == p:
        p_cnt=cnt
    if list(i) == q:
        q_cnt=cnt
    cnt+=1
print(abs(p_cnt-q_cnt))

Submission status: Accepted

Solution code:
import itertools

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

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

for i, c in enumerate(CombinationN):
    if c == P:
        a = i
    if c == Q:
        b = i

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

c = 0
for s in itertools.permutations(range(1, n+1), n):
    c += 1
    if s == p:
        a = c
    if s == q:
        b = c

ans = abs(a - b)
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import math
import itertools
n = int(input())
p = [int(i) for i in input().split()]
q = [int(i) for i in input().split()]

tmp = [i+1 for i in range(n)]
tmp2 = list(itertools.permutations(tmp))
for i in range(len(tmp2)):
    flag1 = True
    flag2 = True
    for j in range(len(p)):
        if tmp2[i][j] != p[j]:
            flag1 = False
        if tmp2[i][j] != q[j]:
            flag2 = False
    if flag1:
        a = i + 1
    if flag2:
        b = i + 1
print(abs(a-b))

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, acos, atan, asin
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
def input(): return sys.stdin.readline().strip()
def STR(): return input()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
sys.setrecursionlimit(10 ** 9)
inf = sys.maxsize
mod = 10 ** 9 + 7

n = INT()
p = LIST()
q = LIST()
l = list(permutations(range(1, n + 1), n))
l.sort()
a = 0
b = 0
for i in range(len(l)):
    flagp = True
    flagq = True
    for j in range(n):
        if l[i][j] != p[j]:
            flagp = False
        if l[i][j] != q[j]:
            flagq = False
    if flagp:
        a = i
    if flagq:
        b = i
print(abs(a - b))

Submission status: Accepted

Solution code:
from itertools import permutations
N=int(input())
P=list(map(int,input().split()))
Q=list(map(int,input().split()))
np,nq=0,0
for i,V in enumerate(permutations(range(1,N+1))):
    tmp=list(V)
    if all(p==v for p,v in zip(P,V)):
        np=i
    if all(q==v for q,v in zip(Q,V)):
        nq=i
print(abs(np-nq))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from itertools import permutations

N = int(input().strip())
pat_P = tuple(map(int, input().rstrip().split()))
pat_Q = tuple(map(int, input().rstrip().split()))
#-----

perm_list = [ pat for pat in permutations(range(1,N+1))]

a = perm_list.index(pat_P) + 1
b = perm_list.index(pat_Q) + 1
print(abs(a-b))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from itertools import permutations

N = int(input().strip())
pat_P = [ "".join( input().rstrip().split() )][0]
pat_Q = [ "".join( input().rstrip().split() )][0]
#-----

perm_list = [ "".join( map(str, pat) ) for pat in permutations(range(1,N+1))]
perm_list.sort()

a = perm_list.index(pat_P) + 1
b = perm_list.index(pat_Q) + 1
print(abs(a-b))

Submission status: Accepted

Solution code:
import copy


def count_order(l, r, i):
    global a
    if r == []:
        a.append(i)

    if not l:
        return 1

    sum = 0
    for x in l:
        ll = copy.copy(l)
        rr = copy.copy(r)
        if r is not None and r[0] == x:
            rr.pop(0)
        else:
            rr = None
        ll.remove(x)
        sum += count_order(ll, rr, sum + i)

    return sum


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

count_order(list(range(1, n + 1)), p, 0)
count_order(list(range(1, n + 1)), q, 0)
print(abs(a[0] - a[1]))

Submission status: Accepted

Solution code:
import itertools

n = int(input())

al = [int(x) for x in input().split()]
bl = [int(x) for x in input().split()]
l = [int(x) for x in range(1, n+1)]

a, b, flag, i = 0, 0, 0, 0

for v in itertools.permutations(l):
    i += 1
    lv = list(v)
    if al == lv:
        a = i
        flag += 1
    if bl == lv:
        b = i
        flag += 1
    if flag == 2:
        break

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import math
N = int(input())
P_tuple = tuple(map(int, input().split()))
Q_tuple = tuple(map(int, input().split()))

for index, p in zip(range(math.factorial(N)), itertools.permutations(range(1, N + 1))):
    if p == P_tuple:
        a = index + 1
    if p == Q_tuple:
        b = index + 1

print(abs(a - b))

Submission status: Accepted

Solution code:
import itertools
import math
N = int(input())
P = tuple(map(int,input().split(" ")))
Q = tuple(map(int,input().split(" ")))
Nk = math.factorial(N)
per = list(itertools.permutations(range(1,N+1)))
for i in range(Nk):
    if P == per[i]:
        p = i
for j in range(Nk):
    if Q == per[j]:
        q = j
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()))
P_count = 0
Q_count = 0
for i in range(N - 1):
    P_count += (P[i] - 1) * math.factorial(N - 1 - i)
    Q_count += (Q[i] - 1) * math.factorial(N - 1 - i)
    for j in range(i + 1, N - 1):
        if P[j] > P[i]:
            P[j] -= 1
        if Q[j] > Q[i]:
            Q[j] -= 1
result = abs(P_count - Q_count)
print(result)

Submission status: Accepted

Solution code:
import itertools

N = int(input())
A = []
B = tuple(map(int,input().split()))
C = tuple(map(int,input().split()))
cnt1 = 0
cnt2 = 0

for i in range (N+1):
    A.append(i)
A.remove(0)

sum = list(itertools.permutations(A))

for i in sum:
    if tuple(i) == B:
      break
    else:
      cnt1 += 1

for i in sum:
    if tuple(i) == C:
      break
    else:
      cnt2 += 1

print(abs(cnt1 - cnt2))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
nn = []
for i in range(1,n+1):
         nn.append(i)
zisyo = list(map(list,(itertools.permutations(nn))))
b = (-1)
for i in range(len(zisyo)):
         if zisyo[i] == p:
                  a = i
         elif zisyo[i] == q:
                  b = i
if b == (-1):
         print(0)
else:
         print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
import math
import bisect

n = int(input())
al = list(map(int,input().split()))
bl = list(map(int,input().split()))

nl = []
a = 0
b = 0
for i in range(1,n+1) :
  nl.append(i)
  a += al[i-1]*10**(n-i)
  b += bl[i-1]*10**(n-i)

ans = [0 for i in range(math.factorial(n))]
index = -1
for num in itertools.permutations(nl):
  index += 1
  for i in range(1,n+1) :
      ans[index] += num[i-1]*10**(n-i)

print(abs(bisect.bisect_left(ans,a)-bisect.bisect_left(ans,b)))

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()]
p = tuple(p)
q = tuple(q)
x = itertools.permutations(range(1,n+1))
x = list(x)
a = x.index(p)
b = x.index(q)
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = input().split()
Q = input().split()
num = ""
for i in range(1, N+1):
  num += str(i)
a = 0
b = 0
count = 0
for i in list(itertools.permutations(num)):
  count += 1
  if "".join(list(i)) == "".join(P):
    a = count
  if "".join(list(i)) == "".join(Q):
    b = count

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
s1 = tuple(map(int,input().split()))
s2 = tuple(map(int,input().split()))

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

l_ = list(itertools.permutations(l,N))

dic = {}
num = 0
for item in l_:
  dic[item] = num
  num += 1

print(abs(dic[s1]-dic[s2]))

Submission status: Accepted

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

dic = itertools.permutations(range(1, N + 1), N)
count = [False, 0]
for i in dic:
    if list(i) == P:
        if count[0]:
            break
        else:
            count[0] = True
    if list(i) == Q:
        if count[0]:
            break
        else:
            count[0] = True
    if count[0]:
        count[1] += 1

print(count[1])

Submission status: Accepted

Solution code:
import itertools

N = int(input())

P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
d = {}

pattern = itertools.permutations(range(1,N+1),  N)
i = 1
for p in pattern:
    d[p] = i
    i += 1

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

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
np = [i for i in range(1, N+1)]
all_list = list(itertools.permutations(np))
P_num = 0
Q_num = 0

for index, line in enumerate(all_list):
    if list(line) == P:
        P_num = index
    if list(line) == Q:
        Q_num = index

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()))
np = [i for i in range(1, n+1)]

import itertools

all_list = list(itertools.permutations(np))

cnt=0
a, b = 0, 0
for seq in all_list:
  cnt += 1
  if list(seq) == p:
    a = cnt
  if list(seq) == q:
    b = cnt

print(abs(a-b))

Submission status: Accepted

Solution code:
import math

N = int(input())

input_line = input()
Line1 = input_line.split()
Line1 = [int(s) for s in Line1]

input_line = input()
Line2 = input_line.split()
Line2 = [int(s) for s in Line2]

Line1_count = 1
Line2_count = 1

Line1_base = []
Line2_base = []

for z in range(N):
    Line1_base.append(z+1)
    Line2_base.append(z+1)

# print (Line1_base)

for i in range(N):
    q = i+1
    # print("s",i,q)
    # print(Line1[i])
    # print(Line1_base.index(Line1[i]),math.factorial(N-q))

    Line1_count += math.factorial(N-q)*Line1_base.index(Line1[i])
    Line2_count += math.factorial(N-q)*Line2_base.index(Line2[i])
    Line1_base.remove(Line1[i])
    Line2_base.remove(Line2[i])
    # print(Line1_base)
    
    # print(Line1_count)
    # print(Line2_count)
print(abs(Line2_count - Line1_count))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 00:21:01 2020

@author: Kanaru Sato
"""

import itertools as it
n = int(input())

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

L = list(it.permutations(range(1,n+1)))

a = L.index(p)
b = L.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()))

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

Submission status: Accepted

Solution code:
import itertools

n = int(input())
s1 = list(map(int,input().split()))
s2 = list(map(int,input().split()))
count = 0

for i in itertools.permutations(range(1, n + 1)):
  count += 1
  if i == tuple(s1):
    ans1 = count
  if i == tuple(s2):
    ans2 = count

print(abs(ans1 - ans2))

Submission status: Accepted

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

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

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

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

Submission status: Accepted

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
cnt = 1
a = 0
b = 0
for i in itertools.permutations(range(1, n+1)):  # 0, 1, 2
    if tuple(p) == i:
        a = cnt
    if tuple(q) == i:
        b = cnt
    cnt += 1

print(abs(a-b))

Submission status: Accepted

Solution code:
# import bisect
# import copy
# import fractions
# import math
# import numpy as np
# from collections import Counter, deque
from itertools import accumulate,permutations, combinations,combinations_with_replacement,product


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

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







resolve()

Submission status: Accepted

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

import itertools

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

perms = list(map(list, itertools.permutations(range(1, N+1), N)))
perms.sort()
# print(perms)
# print(perms.index([1, 2, 3]))
# print(perms.index([3, 2, 1]))

a = perms.index(P) + 1
b = perms.index(Q) + 1

print(abs(a - b))

Submission status: Accepted

Solution code:
import math
import itertools as it

w = int(input())
p = input()
q = input()

pc = 1
qc = 1

r = list(range(1,w+1))
perm = list(it.permutations(r,w))

for i in range(0, math.factorial(w)-1):
    pl = p.split(' ')
    pln = list([int(n) for n in pl])
    if list(perm[i]) == pln:
        break
    else:pc += 1

for i in range(0, math.factorial(w)-1):
    ql = q.split(' ')
    qln = list([int(n) for n in ql])
    
    if list(perm[i]) == qln:
        break
    else:qc += 1

    
print(abs(pc - qc))

Submission status: Accepted

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

Submission status: Accepted

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

import itertools
l = list(itertools.permutations(range(1, n+1)))
#permutations:順列 combinations:組み合わせ (list, 数字)rCnのnが「数字」で決まる
print(abs(l.index(p) - l.index(q)))