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:
# template by 3xC and starkizard.
# contributors: 

#####################################################################################
from __future__ import division, print_function 

import sys
import os
from collections import Counter, deque, defaultdict
import itertools
import math
import io


"""Uncomment modules according to your need"""


# from bisect import bisect_left, bisect_right, insort
# from heapq import heappop, heapify, heappush
# from random import randint as rn
# from Queue import Queue as Q
# from copy import deepcopy
# from decimal import *
# import re
# import operator

#####################################################################################
# this enables you to write python3 code with PyPy2 (Python 2)
if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

#####################################################################################

"""value of mod"""
MOD = 998244353
mod = 10**9 + 7

"""Uncomment next 4 lines if doing huge recursion"""
# import threading
# threading.stack_size(1<<27)
# sys.setrecursionlimit(10000

def prepare_factorial(mod=mod):
    """ returns two lists, factorial and inverse factorial modulo argument by default 10**9 +7 """
    # Comment code out when you don't need inverse factorial or vice versa
    fact = [1]
    for i in range(1, 200005):
        fact.append((fact[-1] * i) % mod)

    ifact = [0] * 200005
    ifact[200004] = pow(fact[200004], mod - 2, mod)
    for i in range(200004, 0, -1):
        ifact[i - 1] = (i * ifact[i]) % mod

    return fact, ifact

def modinv(n, p):
    """ returns N inverse modulo p """
    return pow(n, p - 2, p)

def ncr(n, r,  fact, ifact):
    """ takes 4 arguments: n , r and factorial and inverse factorial lists"""
    t = (fact[n] * (ifact[r]*ifact[n-r]) % MOD)% MOD
    return t


def get_n(Sum):    
    """this function returns the maximum n for which Summation(n) <= Sum"""
    ans = (-1 + sqrt(1 + 8*Sum))//2
    return ans

def sieve(n):
    """ returns a list of prime numbers till n """
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r



def divs(n, start=1):
    """ returns a list of all divisors till n """
    divisors = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors



def divn(n, primes):
    """ returns the number of divisors, two arguments n and the sieve till n """
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t



def lrfind(d, x, default=-1):
    """ Takes 2 arguments an iterable and an element. returns a tuple (firstoccurence,lastoccurence) -1 if not found """
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1: left = i
            right = i
    if left == -1:
        return default, default
    else:
        return left, right

def gcd(x, y): # math.gcd is slower
    """ returns greatest common divisor of x and y """
    while y:
        x, y = y, x % y
    return x

def check_sorted(a):
    ''' returns True/False '''
    for i in range(len(a)-1):
        if a[i]>a[i+1]:
            return False
    return True
def ceil(n, k=1): return n // k + (n % k != 0) #returns math.ceil but protecting against floating inconsistencies
def input(): return sys.stdin.readline().strip()
def ii(): return int(input()) #inputs integer
def mi(): return map(int, input().split()) # inputting space seperated variables for example x,y,z
def li(): return list(map(int, input().split())) #inputting a space seperated list of integers
def lw(): return input().split() #inputting a space seperated list of strings
def lcm(a, b): return abs(a * b) // gcd(a, b) #returns LCM of two arguments
def prr(a, sep=' ', end='\n'): print(sep.join(map(str, a)), end=end) #For printing an iterable with seperator sep as optional second argument (default : " "), ending character (default: "\n") as optional third
def dd(): return defaultdict(int) #returns a dictionary with values defaulted to 0
def ddl(): return defaultdict(list) #returns a dictionary with values defaulted to []
def write(s): return sys.stdout.write(s)












###################################################################

def main():
    #CODE GOES HERE:
    n=ii()
    p=li()
    q=li()
    l=list(itertools.permutations(sorted(p)))
    print(abs(l.index(tuple(p))-l.index(tuple(q))))













    
""" -------- Python 2 and 3 footer by Pajenegod and c1729 ---------"""

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill();
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)


class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s: self.buffer.write(s.encode('ascii'))
            self.read = lambda: self.buffer.read().decode('ascii')
            self.readline = lambda: self.buffer.readline().decode('ascii')


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

""" main function"""

if __name__ == '__main__':
    main()
    # threading.Thread(target=main).start()

Submission status: Accepted

Solution code:
import itertools

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

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

for i in itertools.permutations(lis, len(lis)):
    m.append(i)

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

Submission status: Accepted

Solution code:
import itertools

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

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


print(abs(p-q))

Submission status: Accepted

Solution code:
# import sys
# sys.setrecursionlimit(10 ** 6)
import bisect
# from decorator import stop_watch
# 
# 
# @stop_watch
def solve(N, Ps, Qs):
    def dfs(s, perm):
        if len(s) == N + 1:
            perm.append(int(s))
            return perm
        for i in range(1, N + 1):
            if not str(i) in s:
                perm = dfs(s + str(i), perm)
        return perm

    perm = dfs('0', [])

    p = int(''.join(Ps))
    q = int(''.join(Qs))

    print(abs(bisect.bisect_right(perm, p) - bisect.bisect_right(perm, q)))


if __name__ == '__main__':
    N = int(input())
    Ps = input().split()
    Qs = input().split()
    solve(N, Ps, Qs)

Submission status: Accepted

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

p = 0
q = 0
for i,r in enumerate(itertools.permutations([i+1 for i in range(N)])):
    if P == r:
        p = i+1
    if Q == r:
        q = i+1
    if p and q:
        break

print(abs(p-q))

Submission status: Accepted

Solution code:
import itertools

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

item = []
for i in range(1,N + 1):
    item.append(str(i))
lst = list(itertools.permutations(item))

item2 = []
for l in lst:
    item2.append(''.join(l))

a = abs(item2.index(P) - item2.index(Q))
print(a)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import itertools
N = int(input())
P = [p for p in map(int,input().split())]
Q = [q for q in map(int,input().split())]

NL = [n for n in range(1,N+1)]

V = [list(v) for v in itertools.permutations(NL)]

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

print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations

def main():
    n = int(input())
    p = list(map(int, input().split()))
    q = list(map(int, input().split()))
    ns = [i for i in range(1,n+1)]
    l = list(permutations(ns,n))
    pt = tuple(p)
    qt = tuple(q)
    print(abs(l.index(pt)-l.index(qt)))

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()))
l=[]
for i in range(1,n+1):
    l.append(i)
l=list(itertools.permutations(l))
l=sorted(l)
k=1
for i in range(1,n+1):
    k*=i
pp=0
qq=0
if p==q:
    print(0)
else:
    for j in range(k):
        if l[j]==p:
            pp=j+1
        elif l[j]==q:
            qq=j+1
    print(abs(pp-qq))

Submission status: Accepted

Solution code:
from itertools import permutations

def readinput():
    n=int(input())
    P=tuple(map(int,input().split()))
    Q=tuple(map(int,input().split()))
    return n,P,Q

def main(n,P,Q):
    permlist=permutations(range(1,n+1))
    sortedList=sorted(permlist)
    #print(sortedList)
    np=sortedList.index(P)
    nq=sortedList.index(Q)
    return abs(np-nq)

if __name__=='__main__':
    n,P,Q=readinput()
    ans=main(n,P,Q)
    print(ans)

Submission status: Accepted

Solution code:
import itertools
X = int(input())
P = tuple(map(int, input().split(" ")))
Q = tuple(map(int, input().split(" ")))
comb = list(itertools.permutations(range(1, X+1),X))
a = comb.index(P)
b = comb.index(Q)
print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import permutations

def solve(N, P, Q):
    vals = [i for i in range(1, N + 1)]
    perms = list(permutations(vals))
    print(abs(perms.index(P) - perms.index(Q)))

if __name__ == "__main__":
    N = int(input())
    P = tuple(map(int, input().split()))
    Q = tuple(map(int, input().split()))
    solve(N, P, Q)

Submission status: Accepted

Solution code:
from collections import deque

def solve(N, P, Q):
    stack = deque()
    vals = [i for i in range(1, N + 1)]
    for idx, next_val in enumerate(vals):
        stack.append([[next_val], vals[: idx] + vals[idx + 1:]])
    a, b = -1, -1
    counter = 0
    while stack:
        cur_list, rest = stack.popleft()
        if not rest:
            counter += 1
            a = counter if cur_list == P else a
            b = counter if cur_list == Q else b
            if 0 < a and 0 < b:
                print(abs(a - b))
                return

        for idx, next_val in enumerate(rest):
            stack.append([cur_list + [next_val], rest[: idx] + rest[idx + 1:]])

if __name__ == "__main__":
    N = int(input())
    P = list(map(int, input().split()))
    Q = list(map(int, input().split()))
    solve(N, P, Q)

Submission status: Accepted

Solution code:
import itertools

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

for i in range(1,N+1):
    order.append(i)

#print(coordinate)

count = 0
for vect in itertools.permutations(order):
    #print(vect)
    count +=1
    if vect == P:
        a = count
    if vect ==Q:
        b = count

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

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

P = int(''.join(P))
Q = int(''.join(Q))

lst = []
for a in list(itertools.permutations(range(1, N + 1))):
    a = [str(b) for b in a]
    a = ''.join(a)
    a = int(a)

    lst.append(a)

lst.sort()
dic = {}
for i, a in enumerate(lst):
    dic[a] = i + 1

ans = abs(dic[P] - dic[Q])
print(ans)

Submission status: Accepted

Solution code:
import itertools

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

cnt = 0
for i in list(itertools.permutations(N)):
    cnt += 1
    if i == P:
        a = cnt
    if i == Q:
        b = cnt
        
print(abs(a-b))

Submission status: Accepted

Solution code:
n = int(input())
ps = tuple(map(int, input().split()))
qs = tuple(map(int, input().split()))

from itertools import permutations

l = list(permutations(range(1, n+1)))

print(abs(l.index(ps) - l.index(qs)))

Submission status: Accepted

Solution code:
from collections import deque
import numpy as np
from math import factorial

n = int(input())

ps = deque(map(lambda x: int(x) - 1, input().split()))

qs = deque(map(lambda x: int(x) - 1, input().split()))

def l_to_num(l):
    ans = 0
    
    n = len(l)
    order = np.arange(n)
    n -= 1
    fn = factorial(n)
    for _ in list(range(n)):
        tmp = l.popleft()
        ans += order[tmp] * fn
        fn //= n
        order[tmp] = 1 << 31
        order[tmp+1:] -= 1
        n -= 1
    
    return ans

print(abs(l_to_num(ps) - l_to_num(qs)))

Submission status: Accepted

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

A = list(permutations(P))
A.sort()
print(abs(A.index(tuple(P)) - A.index(tuple(Q))))

Submission status: Accepted

Solution code:
import itertools
n = int(input())
P = list(map(str, input().split()))
Q = list(map(str, input().split()))
p = ''
for e in P:
  p += e
p = int(p)
q = ''
for e in Q:
  q += e
q = int(q)
l = [str(i) for i in range(1, n + 1)]
r = itertools.permutations(l, n)
a = []
for v in r:
  s = ''
  for e in v:
    s += e
  s = int(s)
  a.append(s)
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()))

n = 0
s = 0

S = list(itertools.permutations(range(1, N+1)))
for i, item in enumerate(S):
    if P == item:
        n = i
    if Q == item:
        s = i
    if s > 0 and n > 0:
        break

print(abs(s-n))

Submission status: Accepted

Solution code:
import itertools

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

data = sorted(q_list)

l = list(itertools.permutations(data, n))
for i in range( len(l) ):
    l[i] = list(l[i])

print( abs( l.index(p_list) - l.index(q_list) ) )

Submission status: Accepted

Solution code:
import itertools

N = int(input())
NP = list(itertools.permutations(range(N), N))
P = tuple(map(lambda s: int(s) - 1, input().split()))
Q = tuple(map(lambda s: int(s) - 1, input().split()))

ans = abs(NP.index(P) - NP.index(Q))
print(ans)

Submission status: Accepted

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

## Library

import sys
from fractions import gcd
import math
from math import ceil,floor
import collections
from collections import Counter
import itertools

## input

# n=int(input())
# A,B,C,D=map(int, input().split())
# string = input()
# yoko = list(map(int, input().split()))
# tate = [int(input()) for _ in range(N)]
# N, M = map(int,input().split()) 
#    P = [list(map(int,input().split())) for i in range(M)]

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

Ptuple = tuple(P)
Qtuple = tuple(Q)

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

count = 0
num = 1
tmp1 = 0
tmp2 = 0

for j in itertools.permutations(tmp):
    if j == Ptuple:
        tmp1 = num
        count += 1
    if j == Qtuple:
        tmp2 = num
        count += 1
    if count == 2:
        print(abs(tmp1-tmp2))
        sys.exit()
    num += 1

Submission status: Accepted

Solution code:
import itertools

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

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

cp = 0
cq = 0

for i in range(len(p)):
    if p[i] == P:
        cp = i + 1
    if p[i] == Q:
        cq = i + 1

print(abs(cp-cq))

Submission status: Accepted

Solution code:
#C
from itertools import permutations
N=int(input())
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
num=[i for i in range(1,N+1)]
L=permutations(num,N)
L=sorted(L)

for i in range(len(L)):
    if L[i]==P:
        a=i
    if L[i]==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()))
r = sorted(p)
r = list(itertools.permutations(r, n))
a, b = -1, -1
idx = 0
while True:
    for i in range(n):
        if r[idx][i] != p[i]:
            break
        if i == n - 1:
            a = idx
    for i in range(n):
        if r[idx][i] != q[i]:
            break
        if i == n - 1:
            b = idx
    if a != -1 and b != -1:
        break
    idx += 1
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
import collections
seq = [i+1 for i in range(n)]
li = itertools.permutations(seq)
dic = collections.defaultdict()
for i,  each in enumerate(li):
    dic[each] = i

print(abs(dic[p] - dic[q]))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
a = [ str(x) for x in range(1,n+1)]
jun = list(itertools.permutations(a))
p = list(map(str, input().split()))
q = list(map(str, input().split()))
p = ''.join(p)
q = ''.join(q)
a = []

for i in jun:
    i = list(i)
    a.append(''.join(i))
x = a.index(p)
y = a.index(q)
print(abs(x-y))

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(range(1,n+1)))
a=0
b=0
for num,i in enumerate(per):
    if i==p: a=num+1
    if i==q: b=num+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()))
comb = sorted(list(permutations([i for i in range(1, N+1)], N)))
print(abs((comb.index(P) + 1) - (comb.index(Q) + 1)))

Submission status: Accepted

Solution code:
from itertools import permutations
import numpy as np
n=int(input())
nn=np.arange(1,n+1).tolist()
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))

s=list(permutations(nn))

a=s.index(a)
b=s.index(b)
print(abs(a-b))

Submission status: Accepted

Solution code:
n=int(input())
import math
p=list(map(int,input().split()))
q=list(map(int,input().split()))
pn=0
qn=0
for i in range(n):
  pn+=math.factorial(n-i-1)*(p[i]-1)
  qn+=math.factorial(n-i-1)*(q[i]-1)
  po=p[i]
  qo=q[i]
  p = [j-1 if j>po else j for j in p]
  q = [k-1 if k>qo else k for k in q]
print(abs(pn-qn))

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
#print(P,Q)
l = [i for i in range(1,N+1)]
count = 1
count_p = 0
count_q = 0

for v in itertools.permutations(l):
    #print(v)
    if v == P:
        count_p = count
    if v == Q:
        count_q = count

    if (count_p != 0) & (count_q != 0):
        ans = abs(count_p - count_q)
        break
    else:
        count += 1

print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations

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

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

C = list(permutations(N))

for i, c in enumerate(C):
    if list(c) == list(P):
        f = i
    if list(c) == Q:
        s = i
print(abs(s-f))

Submission status: Accepted

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

fact = [1]
for i in range(1,8+1):
  fact.append(fact[i-1]*i)


def seq_to_index(seq):
  #print?g()
  seq_len=len(seq)
  unused_val=[i+1 for i in range(seq_len)]
  index=0
  for i in range(seq_len):
  #for i in reversed(range(0,seq_len)):
    ##print?g(i)
    #先頭の数字*それまでに通過してきた組み合わせ
    coeff = seq[i]
    coeff_index_in_unused = unused_val.index(coeff)
    index+=coeff_index_in_unused*fact[seq_len-1-i]
    #使用済みの数は削除
    #print?g(coeff,
    #unused_val,
    #coeff_index_in_unused,
    #index,
    #fact[seq_len - 1 - i])

    unused_val.remove(coeff)

  #print?g()
  return index
    
n=input()

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

pindex=seq_to_index(P)
qindex=seq_to_index(Q)

#print?g(pindex)
#print?g(qindex)

print(qindex-pindex if qindex>pindex else pindex-qindex)

Submission status: Accepted

Solution code:
import itertools

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

perms = list(itertools.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()))

n_p = list(itertools.permutations([i + 1 for i in range(n)], n))
a = -1
b = -1
for i in n_p:
    if a != -1 and b != -1:
        break
    if i == p:
        a = n_p.index(i)
    if i == q:
        b = n_p.index(i)

print(abs(a - b))

Submission status: Accepted

Solution code:
import sys
import itertools

input = sys.stdin.readline

def slove():
    n = int(input())
    P = tuple(map(int,input().split()))
    Q = tuple(map(int,input().split()))
    """
    print(P)
    print(Q)
    """
    count = 0
    for item in itertools.permutations(range(1,1+n)):
        if P == item:
            a = count
        if Q == item:
            b = count
        count += 1
    print(abs(a-b))


if __name__ == "__main__":
    slove()

Submission status: Accepted

Solution code:
def exclude(cs, s):
    return [x for i, x in enumerate(cs) if i not in s]


def createLine(line, length):
    if length <= 0 or length > len(line):
        return []
    result = []
    _createLine(line, length, [], result)
    # print(result)
    return result


def _createLine(line, length, progress, result):
    if length == 0:
        result.append(progress)
        return

    for i in range(len(line)):
        _createLine(exclude(line, [i]), length - 1,
                    progress + [line[i]], result)


N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
line = [i for i in range(1, N + 1)]
string = createLine(line, N)
print(abs(string.index(Q)-string.index(P)))

Submission status: Accepted

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

import itertools

a, b = 0, 0
for i, s in enumerate(itertools.permutations(sorted(P))):
  if s == tuple(P):
    a = i
  if s == tuple(T):
    b = i

print(abs(a-b))

Submission status: Accepted

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

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

pcount, qcount = 0, 0
for x, y in zip(p, q):
    pval.remove(int(x))
    pcount += len([i for i in pval if i <= int(x)-1])*math.factorial(len(pval))
    qval.remove(int(y))
    qcount += len([i for i in qval if i <= int(y)-1])*math.factorial(len(qval))
    
print(abs(pcount-qcount))

Submission status: Accepted

Solution code:
from collections import deque

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

p = int(''.join(p))
q = int(''.join(q))

n_list = []
que = deque([[0,[i+1 for i in range(n)]]])
num = 0
temp_list = []

while len(que) != 0:
    temp = que.popleft()
    if len(temp[1]) == 0:
        n_list.append(temp[0])
        continue
    for i in range(len(temp[1])):
        num = 0
        temp_list = []
        for j in range(len(temp[1])):
            temp_list.append(temp[1][j])
        num += temp_list[i] + temp[0]*10
        temp_list.pop(i)
        que.append([num,temp_list])

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

print(abs(b-a))

Submission status: Accepted

Solution code:
from itertools import permutations

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

s=list(permutations(nn))
#print(s)
a=s.index(p)
b=s.index(q)

print(abs(a-b))

Submission status: Accepted

Solution code:
import math
import itertools
N = int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
a = []
for i in range(1,N+1):
    a.append(i)
junn = list(itertools.permutations(a))
flag = 0
for i in range(math.factorial(N)):
    if p == list(junn[i]):
        pp = i
        if flag == 1:
            break
        flag = 1
    if q == list(junn[i]):
        qq = i
        if flag == 1:
            break
        flag = 1
print(abs(pp-qq))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = tuple(map(int,input().split()))
q = tuple(map(int,input().split()))
ls = list(itertools.permutations(range(1,n+1))) 
print(abs(ls.index(p)-ls.index(q)))

Submission status: Accepted

Solution code:
def mul(n):
  s=1
  for t in range(1,n+1):
    s=s*t
  return s

def f(x):
  result=0
  N=len(x)
  for i in range (N):
    k=0
    for j in range(i,N):
      if x[i]>x[j]:
        k=k+1
    result=result+k*mul(N-i-1)
  return result

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

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

Submission status: Accepted

Solution code:
import sys
import itertools
input = lambda: sys.stdin.readline().rstrip()

def main():
    n = int(input())
    p = tuple([int(i) for i in input().split()])
    q = tuple([int(i) for i in input().split()])
    seq = tuple(range(1, n+1))
    num_p = 0
    num_q = 0
    cnt = 0
    for i in itertools.permutations(seq):
        cnt += 1
        if i == p:
            num_p = cnt
        if i == q:
            num_q = cnt
    print(abs(num_p-num_q))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools
n=int(input())
p=[int(x)-1 for x in input().split()]
q=[int(x)-1 for x in input().split()]

a=-1
b=-1
for i,case in enumerate(itertools.permutations(range(n))):
  if all([1 if p[i]==case[i] else 0 for i in range(n)]):
    a=i
  if all([1 if q[i]==case[i] else 0 for i in range(n)]):
    b=i
  if a >= 0 and b >= 0:
    break
print(abs(a-b))

Submission status: Accepted

Solution code:
N = int(input())
p1 = tuple(map(int,input().split()))
p2 = tuple(map(int,input().split()))
def dfs(pair=[]):
  global lst
  if len(pair) == N:
    lst.append(tuple(pair))
  else:
    for j in range(1,N+1):
      if j not in pair:
        pair.append(j)
        dfs(pair)
        pair.pop()

lst = []
dfs()
lst.sort()
print(abs(lst.index(p1) - lst.index(p2)))

Submission status: Accepted

Solution code:
import itertools
import sys


def input(): return sys.stdin.readline().strip()
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def S(): return input()
def LS(): return input().split()


n = I()
p = tuple(LS())
q = tuple(LS())

num = [str(i) for i in range(1, n + 1)]
perm = list(itertools.permutations(num, n))
ans = abs(perm.index(p) - perm.index(q))
print(ans)

Submission status: Accepted

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

import itertools
seq = range(1,n+1)
dic=list(itertools.permutations(seq))
a=dic.index(p)
b=dic.index(q)
print(abs(a-b))

Submission status: Accepted

Solution code:
import math

def f(X):
    N = len(X)
    ret = 0  
    for i in range(N):
        k = 0
        for j in range(i, N):
            if X[i] > X[j]:
                k += 1
        ret += k * math.factorial(N-i-1)
    return ret

N = int(input())

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

a = f(P)
b = f(Q)

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()))
P_int = "".join(map(str, P))
Q_int = "".join(map(str, Q))

l = range(1, N+1)
p = itertools.permutations(l)
c_p = 0
c_q = 0
for ele in p:
    if "".join(map(str, ele)) < P_int:
        c_p += 1
    if "".join(map(str, ele)) < Q_int:
        c_q += 1
print(abs(c_p-c_q))

Submission status: Accepted

Solution code:
import itertools

n=int(input())
l=list(range(1, n+1))
ptn = sorted(list(itertools.permutations(l)))
p=tuple(map(int, input().split()))
q=tuple(map(int, input().split()))

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

Submission status: Accepted

Solution code:
from itertools import permutations
from bisect import bisect_left

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

l = list(permutations(range(1, n+1)))
print(abs(bisect_left(l, q) - bisect_left(l, p)))

Submission status: Accepted

Solution code:
import sys
import itertools
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
p = tuple(map(int,readline().split()))
q = tuple(map(int,readline().split()))
if p == q:
  print(0)
  sys.exit()
l = [i+1 for i in range(N)]
count = 1
a=[]
for v in itertools.permutations(l):
  count += 1
  if v== p or v ==q:
    a.append(count)
print(a[1]-a[0])