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:
import math
def main():
    N = int(input())
    P = list(map(int, input().split()))
    Q = list(map(int, input().split()))

    nlist = [i for i in range(1, N+1)]
    nlist2 = nlist.copy()
    NN = N
    NN -= 1
    tn = math.factorial(NN)
    a, b= 0, 0

    a += P[0] * tn - tn
    b += Q[0] * tn - tn
    nlist.remove(P[0])
    nlist2.remove(Q[0])

    for i in range(1, N):

        NN -= 1
        tn = math.factorial(NN)
        for j in range(len(nlist)):
            if P[i] == nlist[j]:
                nlist.remove(P[i])
                a+=j*tn - tn 
                break
        
        for j in range(len(nlist2)):
            if Q[i] == nlist2[j]:
                nlist2.remove(Q[i])
                b+=j*tn -tn
                break
    

    print(abs(a-b))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import numpy as np
import itertools
input = sys.stdin.readline

N = int(input())
P = tuple(input().split())
Q = tuple(input().split())
p_all = sorted(list(itertools.permutations(P, N)))
q_all = sorted(list(itertools.permutations(Q, N)))
p_in = p_all.index(P)
q_in = q_all.index(Q)
ans = abs(q_in - p_in)
print(ans)

Submission status: Accepted

Solution code:
import math

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

p = 0
q = 0

for i in range(N-1):
	tmp = 0
	n = P.pop(0)
	for x in range(N):
		if not (x+1 in P) and x+1 < n : tmp += 1
	p += (n-tmp-1) * math.factorial(N-(i+1))
	
	tmp = 0
	n = Q.pop(0)
	for x in range(N):
		if not (x+1 in Q) and x+1 < n : tmp += 1
	q += (n-tmp-1) * math.factorial(N-(i+1))

print(abs(p-q))

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy,copy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
    n = INT()
    p = LIST()
    q = LIST()
    li = list(permutations(range(1, n+1)))
    print(abs(li.index(tuple(p))-li.index(tuple(q))))

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
def kai(x):
	ans = 1
	i=1
	while x>=i:
		ans = ans*i
		i+=1
	return ans
	

def calc(x, l):
	y=len(l)
	a=l[x]
	cnt = 0
	x+=1
	while x < y:
		if l[x] < a:
			cnt+= 1
		x+=1
	return(cnt)

n=int(input())
p = [int(x) for x in input().split()]
q = [int(x) for x in input().split()]
p_num=0
q_num=0
for i in range(n):
	p_num += kai(n-i-1)*calc(i,p)
	q_num += kai(n-i-1)*calc(i,q)
	
if p_num < q_num:
	t=p_num
	p_num = q_num
	q_num = t
		
print(p_num-q_num)

Submission status: Accepted

Solution code:
import itertools

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

count=1
for i in itertools.permutations(range(1,n+1)):
    if i == p_list:
        num1 = count
    if i == q_list:
        num2 = count
    count += 1

if num1 - num2 <0:
    print (num2-num1)
else:
    print (num1-num2)

Submission status: Accepted

Solution code:
def calc_order(nums):
  n = len(nums)
  order = 1
  ls = sorted(nums)
  for i, v in enumerate(nums[:-1]):
    c = (ls.index(v) - 1) * level_mat(n) // level_mat(n, i+1)
    order += c
    ls.remove(v)
  return order


def level_mat(n, m=None):
  if m is None:
    m = n
  assert n >= m

  if m == 0:
    return 1
  if n == 1:
    return 1
  else:
    return n * level_mat(n-1, m-1)


if __name__ == '__main__':
  n = int(input())
  ps = [int(i) for i in input().split()]
  qs = [int(i) for i in input().split()]
  print(abs(calc_order(ps) - calc_order(qs)))

Submission status: Accepted

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

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

def f(a):
  rank = 0
  for i in range(n-1):  
    left=a[i]-1
    for j in range(i+1):
      if a[j]<a[i]:
        left-=1    
    rank += left * factrial(n-i-1)  
  return rank

print(abs(f(q)-f(p)))

Submission status: Accepted

Solution code:
import itertools

n = int(input())
p = list(map(int, input().split()))
for i in range(len(p)):
	p[i] = p[i]-1
p = tuple(p)
q = list(map(int, input().split()))

a = list(itertools.permutations(range(n)))

for i in range(len(q)):
	q[i] = q[i]-1
q = tuple(q)
print(abs(a.index(p) - a.index(q)))

Submission status: Accepted

Solution code:
import itertools

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

for i in range(n):
    seq.append(i+1)

permutation = list(itertools.permutations(seq))
#print(permutation[0][0])
#print(p)

for i in range(len(permutation)):
    for j in range(n):
        if(p[j] != permutation[i][j]):
            #print(permutation[i])
            #print(p)
            break
        if(j == n-1):
            a = count
    for k in range(n):
        if(q[k] != permutation[i][k]):
            break
        if(k == n-1):
            b = count
    count = count + 1

#print(a)
#print(b)
print(abs(b-a))

Submission status: Accepted

Solution code:
import math

def getPosition(Num, n, i):
    Num_buff = Num[i:]
    # print(Num_buff)
    Num_buff.sort()
    return Num_buff.index(n)



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

a = 0
b = 0

# print(P)
# print(Q)
# print("---")

for i in range(N):
    a += (getPosition(P, P[i], i))*math.factorial(N-(i+1)) 
    b += (getPosition(Q, Q[i], i))*math.factorial(N-(i+1)) 
a += 1
b += 1
if a > b:
    print(a-b)
else:
    print(b-a)
# print(a)
# print(b)

Submission status: Accepted

Solution code:
import math
N = int(input())
H = list(map(int, input().split()))
A = list(map(int, input().split()))
ans = 0
h=0
a=0
L=[]
for i in range(1,N+1):
    L.append(i)
#print(L)
for i in range(N):
    for j in range(N-i):
        if(H[i]==L[j]):
            c=j

    h = h + math.factorial(N-1-i)*(c-1)
    L.remove(H[i])
for i in range(1,N+1):
    L.append(i)
for i in range(N):
    for j in range(N-i):
        if(A[i]==L[j]):
            c=j

    a = a + math.factorial(N-1-i)*(c-1)
    L.remove(A[i])
ans=h-a
if ans<0:
    ans = ans*(-1)
print(ans)

Submission status: Accepted

Solution code:
import itertools
a = int(input())
j = 1
b = []
c = []

num1 = input().split()
num2 = input().split()
for i in range(0, len(num1)): 
    num1[i] = int(num1[i])
for i in range(0, len(num2)): 
    num2[i] = int(num2[i]) 

if(a>=2 and a<=8):
  while (j<=a):
      b.append(j)
      j = j+1

c = list(itertools.permutations(b))
index1 = c.index(tuple(num1))
index2 = c.index(tuple(num2))
res = index1-index2 
if(res<0):
    print(res*(-1))
else:
    print(res)

Submission status: Accepted

Solution code:
import itertools
import math
n=int(input())
N=math.factorial(n)
P=tuple(map(int,input().split()))
Q=tuple(map(int,input().split()))
l=list(itertools.permutations(range(1,n+1)))
for i in range(N):
    if l[i] == P:
        a = i
for j in range(N):
    if l[j] == Q:
        b = j
print(abs(b-a))

Submission status: Accepted

Solution code:
import math

n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
ansp = 0
ansq = 0
for i in range(n):
    ansp += (p[i]-1)*(math.factorial(n-i-1))
    #print((p[i]-n-1))
    #print(ansp)
    for j in range(i+1,n):
        if p[j] > p[i]:
            p[j] -= 1
for i in range(n):
    ansq += (q[i]-1)*(math.factorial(n-i-1))
    for j in range(i+1,n):
        if q[j] > q[i]:
            q[j] -= 1

print(abs(ansp-ansq))

Submission status: Accepted

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

def kaijo(n):
  if n <= 0:
    return 0
  else:
    ret = 1
    for i in range(n):
      ret *= (i+1)
    return ret

num_p, num_q = 0, 0
done = []
for i in range(N):
  num = 0
  for j in range(len(done)):
    if done[j] < P[i]:
      num += 1
    else:
      pass
  #num_p += kaijo(N-(i+1)-num) * (P[i] - 1)
  num_p += kaijo(N-(i+1)) * (P[i] - num)
  done.append(P[i])

done = []
for i in range(N):
  num = 0
  for j in range(len(done)):
    if done[j] < Q[i]:
      num += 1
    else:
      pass
  num_q += kaijo(N-(i+1)) * (Q[i] - num)
  done.append(Q[i])

print(abs(num_p - num_q))

Submission status: Accepted

Solution code:
import itertools

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

DICT_NUM = sorted(itertools.permutations(P))

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

Submission status: Accepted

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

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

kaijou_ls = [0]*N

for i in range(N):
    kaijou_ls[i] = kaijou(i+1)

#dp
def count_order(A,k):
    if k==1:
        return 1
    else:
        B = A[N-k:]
        b = B[0]
        C = B.copy()
        C.sort()
        order = C.index(b)*kaijou_ls[k-2]

        return order+count_order(A,k-1)

print(abs(count_order(P,N)-count_order(Q,N)))

Submission status: Accepted

Solution code:
import math
import itertools

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

p_list = [int(i) for i in P.split(" ")]
q_list = [int(i) for i in Q.split(" ")]

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

p_num = 1
q_num = 1
for i in itertools.permutations(n):
    if list(i)==p_list:
        a = p_num
    if list(i)==q_list:
        b = q_num
    p_num += 1
    q_num += 1

print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

in1 = int(input())
in2 = [input().strip().rsplit(" ") for i in range(2)]
count = 0 
for i in itertools.permutations(range(1, in1+1)):
    if in2[0] == list(map(str, i)):
      ans1 = count
    if in2[1] == list(map(str, i)):
      ans2 = count

    count += 1

print(abs(ans2 - ans1))

Submission status: Accepted

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

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

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

r = list(itertools.permutations(range(1,n+1)))

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

Submission status: Accepted

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

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

Submission status: Accepted

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

#Pind = []
#Qind = []
R = []
for i in range(N):
#    Pind.append( P.index(i+1) )
#    Qind.append( Q.index(i+1) ) 
    R.append( i+1 ) 
#print(Pind)
#print(Qind)
#print(R)

import itertools
cnt = 1
for v in itertools.permutations(R, N): 
#    print(list(v))
    if list(v) == P: 
       Porder = cnt
    if list(v) == Q: 
       Qorder = cnt
    cnt += 1
#print(Qorder)
#print(Porder)
sol = abs(Qorder-Porder)
print(sol)

Submission status: Accepted

Solution code:
import math

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

def judgement(n, pos):
    return (int(pos) - 1) * math.factorial(n - 1)

def position(target, list):
    pos = 0
    for i in list:
        if (int(target) > int(i)):
            pos += 1
    return pos + 1

def calculateRank(list):
    targetNum = 0
    rank = 0
    for i in range(N - 1):
        targetNum = list[0]
        list.pop(0)
        targetPosition = position(targetNum, list)
        rank += judgement(N - i, targetPosition)

    return rank

rankA = calculateRank(P)
rankB = calculateRank(Q)

print(abs(rankA - rankB))

Submission status: Accepted

Solution code:
n = int(input())
p = [i for i in map(int, input().split())]
q = [i for i in map(int, input().split())]

sorted_list = sorted(p)
all_list = []

def listExcludedIndices(data, indices=[]):
	return [x for i, x in enumerate(data) if i not in indices]

def permutationListRecursive(data, r):
	if r <= 0 or r > len(data):
		return []
	
	result = []
	_permutationListRecursive(data, r, [], result)
	return result

def _permutationListRecursive(data, r, progress, result):
	if r == 0:
		result.append(progress)
		return
	
	for i in range(len(data)):
		_permutationListRecursive(listExcludedIndices(data, [i]), r - 1, progress + [data[i]], result)


a = -1
b = -1

for i, list_ in enumerate(permutationListRecursive(sorted_list, n)):
	#print(list_)
	if list_ == p:
		a = i

	if list_ == q:
		b = i

	if a != -1 and b != -1:
		break

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
X = permutations(list(range(1, N+1)))
for i, x in enumerate(X):
    x = list(x)
    if x == P:
        p = i
    if x == Q:
        q = i
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()))
list_a = list(range(1,N+1))
tuple_a = tuple(list_a)
ptr = list(itertools.permutations(tuple_a))
ptr_num = len(list(itertools.permutations(tuple_a)))
for i in range(0,ptr_num):
  if ptr[i] == tuple(P):
    P_num=i+1
  if ptr[i] == tuple(Q):
    Q_num=i+1
print(abs(P_num-Q_num))

Submission status: Accepted

Solution code:
N = int(input())
p = tuple(int(x) for x in input().split())
q = tuple(int(x) for x in input().split())
r = []
a=0
c1 =0
c2 =0
import itertools

def for_factorial(n):
    val = 1
    for i in range(2, n + 1):
        val *= i
    return val

a =for_factorial(N)

r =list(itertools.permutations(range(1,N+1)))
for i in range(a):
    if p == r[i]:
        c1 = i+1

for i in range(a):
    if q == r[i]:
        c2 = i+1

if c1 >= c2:
    print(c1-c2)
else:
    print(c2-c1)

Submission status: Accepted

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

import math
import itertools

dia = list(itertools.permutations([i+1 for i in range(n)]))

for i in range(len(dia)):
    if list(dia[i]) == p:
        sc_p = i
    if list(dia[i]) == q:
        sc_q = i

print(abs(sc_p - sc_q))

Submission status: Accepted

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

#print(junretsu)
count = 1
a = 0
for x in junretsu:
    if(list(x) == P):
        a = count
    count += 1
#print(a)
count = 1
b = 0
for x in junretsu:
    if(list(x) == Q):
        b= count
    count += 1
#print(b)
print(abs(b-a))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 21:13:02 2020

@author: masat
"""
import math

N = int(input())
P_list = list(map(int, input().split()))
Q_list = list(map(int, input().split()))

def jishojun(a_list):
    dist = 0
    for i in range(N):
        sorted_slice = sorted(a_list[i:])
        dist += math.factorial(N-i-1) * sorted_slice.index(a_list[i])
    return dist

answer = abs(jishojun(P_list) - jishojun(Q_list))
print(answer)

Submission status: Accepted

Solution code:
import itertools

N = int(input())
P = str(input()).split(" ")
Q = str(input()).split(" ")

#順列の組み合わせすべてを生成して数値として格納
All = []

for i in itertools.permutations(P):
    stack = ""
    for j in i :
        stack = stack + j
    All.append(int(stack))

All.sort()

#Pを数値化
stack = ""
for i in P:
    stack = stack + i
P = int(stack)
#Qを数値化
stack = ""
for i in Q:
    stack = stack + i
Q = int(stack)

#インデックスを取得
P = All.index(P)+1
Q = All.index(Q)+1

print(abs(P-Q))

Submission status: Accepted

Solution code:
import itertools
import math

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

N_l = list(itertools.permutations(P_org))
N_fac = math.factorial(N)

a = 1
b = 1
for x in range(N_fac):
    if (P == list(N_l[x])):
        a += x
    if (Q == list(N_l[x])):
        b += x    
        
print(abs(a-b))

Submission status: Accepted

Solution code:
import itertools

i = int(input())
P = input().split()
Q = input().split()

list_to_permute = []
for each in range(1, i+1):
    list_to_permute.append(each)

list_of_all_permutes = list(itertools.permutations(list_to_permute))


# Calculatation
P = tuple(int(element) for element in P)
Q = tuple(int(element) for element in Q)
a = list_of_all_permutes.index(P) + 1
b = list_of_all_permutes.index(Q) + 1 

print(abs(a-b))

Submission status: Accepted

Solution code:
import numpy as np
import itertools
from sys import stdin
lines = stdin.readlines()
 
N = int(lines[0])
P = list(map(str, lines[1].split()))
Q = list(map(str, lines[2].split()))

permu = []
for a in range(N):
  permu.append(str(a + 1))

#print(permu)

cnt_a = 1
for p in itertools.permutations(permu):
  cnt_a += 1
  p_act = np.array(p)
  p_test = np.array(P)
  if (p_test == p_act).all() == True:
    a = cnt_a

cnt_b = 1
for q in itertools.permutations(permu):
  cnt_b += 1
  q_act = np.array(q)
  q_test = np.array(Q)
  if (q_test == q_act).all() == True:
    b = cnt_b

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()))
a=b=1
l=[i for i in range(1,N+1)]
m=[i for i in range(1,N+1)]
for i in range(N):
  #print("===P[i]===", P[i])
  #print(l.index(P[i]), math.factorial(N-i-1))
  if N-i-1 < 0:
    pass
  else:
    a += l.index(P[i])*math.factorial(N-i-1)
  #print("l", l)
  if not i==N-1:
    l.pop(l.index(P[i]))
for i in range(N):
  if N-i-1 < 0:
    pass
  else:
    b += m.index(Q[i])*math.factorial(N-i-1)
  if not i==N-1:
    m.pop(m.index(Q[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()])


n = N - 1
num_list = [i+1 for i in range(N)]

num_list_set = list(itertools.permutations(num_list))
a = num_list_set.index(P)
b = num_list_set.index(Q)

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

def count_dict(N, P):
  sum_p = 1
  count = 0
  for p in P[:-1]:
    P_rest = sorted(P[count:])
    p_order = P_rest.index(p)
    sum_p += (p_order) * math.factorial(N-count-1)
    count += 1
  return sum_p

a = count_dict(N, P)
b = count_dict(N, Q)

print(abs(a-b))

Submission status: Accepted

Solution code:
n = int(input())

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

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

p_copy = p.copy()
q_copy = q.copy()

def mycalc(ls,th):
    ans = [ i for i in ls if i<th ]
    return ans

ans = mycalc(p,7)

a = 0
for i in range(n-2):
    p_copy.remove(p[i])
    g = mycalc(p_copy,p[i])
    a += (len(g))*ls[n-i-1]
if p_copy[0]<p_copy[1]:
    a += 1
else:
    a += 2

r = list(range(1,n+1))
b = 0
for i in range(n-2):
    q_copy.remove(q[i])
    g = mycalc(q_copy,q[i])
    b += (len(g))*ls[n-i-1]
if q_copy[0]<q_copy[1]:
    b += 1
else:
    b += 2

print(abs(a-b))

Submission status: Accepted

Solution code:
from itertools import*
n=int(input())
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))
c=list(permutations(range(1,n+1)))
print(abs(c.index(a)-c.index(b)))

Submission status: Accepted

Solution code:
def kaijou(n):
  result = 1
  for i in range(1, n+1):
    result *= i
  return result

def nanbanme(l, n):
  for i in range(len(l)):
    if l[i] == n:
      return i
  
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
p_n = [i for i in range(1, n+1)]
q_n = [i for i in range(1, n+1)]

pp, qq = 1, 1

for i in range(n):
  if p[i] != min(p_n):
    pp += kaijou(n-i-1) * nanbanme(p_n, p[i])
  p_n.remove(p[i])
    
  if q[i] != min(q_n):
    qq += kaijou(n-i-1) * nanbanme(q_n, q[i])
  q_n.remove(q[i])
    
print(abs(pp-qq))

Submission status: Accepted

Solution code:
import itertools
N = int(input())
a=tuple(map(int,input().split()))
b=tuple(map(int,input().split()))
cnt = 0
cnt2 = 0
for i in itertools.permutations(range(1,N+1)):
  if a == i:
    break
  cnt += 1
for s in itertools.permutations(range(1,N+1)):
  if b == s:
    break
  cnt2 += 1
print(abs(cnt-cnt2))

Submission status: Accepted

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

def factorial(n):
    if n < 2:
        return 1
    ret = 1
    for i in range(2, n + 1):
        ret *= i
    return ret

import itertools
seq = list(map(lambda x: x + 1, list(range(n))))
ptr = list(itertools.permutations(seq))

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

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

def kaisa(x):
  a = 1
  for i in range(1,x + 1,1):
    a += a *i
  return a 
    
a_ = 1
b_ = 1

for i in range(1,n,1):
  a_ += sorted(a).index(a[0]) * kaisa(n-1-i)
  del a[0]
  b_ += sorted(b).index(b[0]) * kaisa(n-1-i)
  del b[0]
  
print(abs(a_ - b_))

Submission status: Accepted

Solution code:
import itertools
num = int(input())
p = tuple(input().split())
q = tuple(input().split())
lister = [str(s) for s in range(1,num+1)]
comb = list(itertools.permutations(lister))
memory1 = 0
memory2 = 0
for t in range(len(comb)):
    if p == comb[t]:
        memory1 = t+1
    if q == comb[t]:
        memory2 = t+1
print(abs(memory1-memory2))

Submission status: Accepted

Solution code:
def cnt(kurai, num, detalist):
    jun_i = (num - 1 - sum(detalist[:(num-1)])) * kaijo[kurai-1]
    return jun_i

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

kaijo = [1, 1, 2, 6, 24, 120, 720, 5040]
detalist_p = [0] * n
detalist_q = [0] * n

pno = 1
qno = 1
for i in range(n-1):
    pno += cnt(n-i, P[i], detalist_p)
    detalist_p[P[i]-1] = 1

    qno += cnt(n-i, Q[i], detalist_q)
    detalist_q[Q[i]-1] = 1

print(abs(pno - qno))

Submission status: Accepted

Solution code:
import math
n = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
x = 0
y = 0
cnt=0
for i in range(n):
  for l in range(i):
    if p[i] > p[l]:
      cnt += 1
  x += (p[i] - 1 - cnt)*(int(math.factorial(n - 1 - i)))
  cnt = 0
for i in range(n):
  for l in range(i):
    if q[i] > q[l]:
      cnt += 1
  y += (q[i] - 1 - cnt)*(int(math.factorial(n - 1 - i)))
  cnt = 0
print(abs(x-y))

Submission status: Accepted

Solution code:
import sys
import math
import bisect
stdin = sys.stdin
mod = 10**9 + 7

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
sa = lambda h: [list(map(int, stdin.readline().split())) for i in range(h)]

def factorial(n):
    if n == 1:
        return n
    elif n==0:
        return 0
    return n * factorial(n-1)

n = ni()

p = na()
q = na()
def check(pq):
    ans = factorial(n)
    a = list(range(1,n+1))
    for i in range(n):
        l = n - i
        pqi = pq[i]
        index = a.index(pqi)
        ans -= factorial(max(l-1, 0)) * max(l-index, 0)
        a.remove(pqi)
    return ans
print(abs(check(p) - check(q)))

Submission status: Accepted

Solution code:
import math

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

count = 0

def keisan(t):
    num = []
    q = 0
    c = 0
    tmp = 1
    while q < N:
        if int(t[q]) > tmp and (tmp in num) is False:
            c += math.factorial(N - q - 1)
            tmp += 1
        elif int(t[q]) == tmp:
            q += 1
            num.append(tmp)
            tmp = 1
        else:
            tmp += 1
    return c


count += abs(keisan(P) - keisan(Q))

print(count)

Submission status: Accepted

Solution code:
number_select = int(input())
A = list(map(str,input().split()))
B = list(map(str,input().split()))
A_total = 0
B_total = 0
listA = []
def pattern(a):
    b = 1
    for r in range(1,a+1):
        b = b * r
    return b
def list_A(a):
    for i in range(1,a+1):
        listA.append(str(i))
list_A(number_select)
for i in range(number_select-1):
    A_total += listA.index(A[i]) * pattern(number_select-i-1)
    listA.remove(A[i])
listA.clear()
list_A(number_select)
for r in range(number_select-1):
    B_total += listA.index(B[r]) * pattern(number_select-r-1)
    listA.remove(B[r])
print(abs(A_total-B_total))

Submission status: Accepted

Solution code:
from collections import defaultdict, deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys
import random
import itertools
import math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt


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


def LF(): return list(map(float, input().split()))


def LI_(): return list(map(lambda x: int(x)-1, input().split()))


def II(): return int(input())


def IF(): return float(input())


def LS(): return list(map(list, input().split()))


def S(): return list(input().rstrip())


def IR(n): return [II() for _ in range(n)]


def LIR(n): return [LI() for _ in range(n)]


def FR(n): return [IF() for _ in range(n)]


def LFR(n): return [LI() for _ in range(n)]


def LIR_(n): return [LI_() for _ in range(n)]


def SR(n): return [S() for _ in range(n)]


def LSR(n): return [LS() for _ in range(n)]


def gcd(x, y):
    if y == 0:
        return x
    return gcd(y, x % y)


def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]


def sosu(x):
    for i in range(2, int(sqrt(x)+1)):
        if x % i == 0:
            return False
    return True


mod = 1000000007
inf = float('INF')


def A():
    K, X= LI()

    if (500*K>=X):
        print('Yes')
    else:
        print('No')


    return

# B


def B():
    N=II()
    S=input().rstrip()
    ans=0
    s=0
    for i in S:
        if (i=="A" and S[s+1]=='B' and S[s+2]=='C'):
            ans+=1
        s+=1
    print(ans)



    return

# C


def true():
    S = input()
    S = S[:-1]

    tmp = 0
    for x in range(1 << (len(S)-1)):
        func = S[-1]
        for i in range(len(S)-1):
            if(x & (1 << i)):
                tmp += int(func)
                func = S[-2-i]
            else:
                func = S[-2-i]+func
        tmp += int(func)
    print(tmp)

    return


def flagcounter(x):
    if (x == 0):
        return 0
    return flagcounter(x >> 1)+(x & 1)

def jisyo(P):
    i=1
    S = sorted(P)
    X=0
    N=len(P)
    for p in P:
    
        X+=((S.index(p)+1) * (math.factorial(N-i)))-1
        
        S.remove(p)
        if len(S)==1:
            break
        i+=1
    return X

def C():
    N=II()
    P=LI()
    Q=LI()

    X=jisyo(P)
    Y=jisyo(Q)


    print(abs(X-Y))
        
    return


# D
def D():
    N, K = LI()
    R, S, P = LI()
    T=list(input().rstrip())
    ans = 0
    for j in range(K):
        if T[j] == 'r':
            ans += P
        if T[j] == 'p':
            ans += S
        if T[j] == 's':
            ans += R
    j = 0
    rps=['r','p','s']

    for i in range(K, N):
        if T[j] == T[i]:
            if i+K>=N:
                j += 1
                continue
            T[i]=rps[rps.index(T[i+K])-1]
            j += 1
            continue
        if T[i] == 'r':
            ans += P
        if T[i] == 'p':
            ans += S
        if T[i] == 's':
            ans += R
        j += 1
    print(ans)
    return


def Dsyakutori():

    N, K = LI()
    A = LI()
    MAX = sum(A)
    if MAX < K:
        print(0)
        return
    Temp = MAX
    ans = 1
    for i in range(N):
        Temp = Temp-A[i]
        if (Temp >= K):
            ans += 1
        else:
            T = Temp+A[i]
            break
    Temp = T
    ckeep = N
    for k in range(N):
        c = N-1
        i -= 1
        Temp = T

        for j in range(N):
            Temp = Temp-A[c]
            if (Temp >= K):
                ans += 1

            elif(c < ckeep and i >= 0):
                ans += i
                ckeep = c
                break
            else:
                ckeep = c
                break
            c -= 1
        if i < 0:
            break
        T = T+A[i]
    print(ans)

    return

# E


def E():
    N, M= LI()
    A = LI()
    A.sort(reverse=True)
    B=[0]*(N+1)
    for i in range(1,N+1):
        B[i]=B[i-1]+A[i-1]
    D=[0]*(2*10**5+1)
    for i in range(N):
        D[A[i]]+=1
    for i in range(len(D)-1,0,-1):
        D[i-1]+=D[i]
    l=-1
    r=2*10**5+1
    while r-l>1:
        m=(l+r)//2
        s=0
        for i in range(N):
            s+=D[max(1,m-A[i])]
        if s>=M:
            l=m
        else:
            r=m
    ans=0
    s=0
    for i in range(N):
        v=max(0,r-A[i])
        t=max(0,min(D[v],M-s))
        ans+=B[t]+t*A[i]
        s+=t
    ans+=l*(M-s)
    print(ans)

    
    return

# F


def F():
    N, M = LI()

    value = [0] * M
    power = [0] * M
    for i in range(M):
        a, b = LI()
        value[i] = a
        c = LI()
        L = ['0'] * N
        for k in c:
            L[k - 1] = '1'
        bint = ''.join(L)
        power[i] = int(bint, 2)
    bint = ''.join(list(['1'] * N))
    dp = [inf] * (int(bint, 2)+1)
    t = 0
    cost = 0

    dp[0] = 0
    for s in range(int(bint, 2) + 1):
        for i in range(M):
            t = s | power[i]
            cost = dp[s] + value[i]
            dp[t] = min(dp[t], cost)
    print(-1) if(dp[-1] == inf) else print(dp[-1])

    return

    # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")


def solution(S):
    # write your code in Python 3.6
    N = len(S)

    pass


# Solve
if __name__ == '__main__':

    C()

Submission status: Accepted

Solution code:
import math
import numpy as np

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

a = 1
a_list = list(np.arange(N) + 1)
for i in range(N - 1):
    a += a_list.index(P[i]) * math.factorial(N - (i + 1))
    a_list.remove(P[i])
    
b = 1
b_list = list(np.arange(N) + 1)
for j in range(N):
    b += b_list.index(Q[j]) * math.factorial(N - (j + 1))
    b_list.remove(Q[j])
    
print(abs(a - b))