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: Runtime Error

Solution code:
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))

N = INT()
P = LIST()
Q = LIST()

import itertools

for i, l in enumerate(itertools.permutations(range(1, N+1), N)):
    if list(l) == P:
        a = i+1
    elif list(l) == Q:
        b = i+1

print(abs(a-b))

Submission status: Runtime Error

Solution code:
import itertools
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]

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

print(abs(l.index(a) - l.index(b)))

Submission status: Runtime Error

Solution code:
import itertools
n = int(input())
P = list(map(int, input().replace(' ', '')))
Q = list(map(int, input().replace(' ', '')))
N = [i + 1 for i in range(n)]
per = list(itertools.permutations(N))
lis = []
for oc in per:
    lis.append(int(''.join(map(str, list(oc)))))
a = lis.index(P)
b = lis.index(Q)
print(abs(a - b))

Submission status: Runtime Error

Solution code:
import itertools
n = int(input())
P = list(map(int, input().replace(' ', '')))
Q = list(map(int, input().replace(' ', '')))
N = [i + 1 for i in range(n)]
per = list(itertools.permutations(N))
lis = []
for oc in range(per):
    lis.append(int(''.join(map(str, list(per)))))
a = lis.index(P)
b = lis.index(Q)
print(abs(a - b))

Submission status: Runtime Error

Solution code:
n = int(input())
P = list(map(str, input().split()))
Q = list(map(str, input().split()))
p, q = '' , ''
for i in range(n):
    p += P[i]
    q += Q[i]

a, b = 0, 0
num = 10 ** (n - 1)
count = 0
found = False
while found == False:
    num += 1
    waru = num
    conv_num = ''
    while waru != 0:
        conv_num = str(waru % (n + 1)) + conv_num
        waru = waru // (n + 1)
    if 0 in conv_num:
        pass
    else:
        count += 1
        if conv_num == p:
            a = count
        if conv_num == q:
            b = count
    if p != 0 and q != 0:
        found = True
ans = a - b
if ans < 0:
    ans *= -1
print(ans)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
from itertools import permutations

N = int(input())
# マップの戻り値はlistではないのでリスト形式で返す
P = list(map(int, input().split()))
Q = list(map(int, input().split()))


def count(x):
    i = 0
    # permutations => 渡したlistから順列を作成する。
    for perm in permutations(range(1, N+1)):
        if perm == x:
            return i
        i += 1


print(abs(count(P) - count(Q)))

Submission status: Runtime Error

Solution code:
import itertools

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

nlist = list(itertools.permutations(i for i in range(1,n+1)))

ans = abs(index(nlist,p) - index(nlist,q))

Submission status: Runtime Error

Solution code:
import itertools

def AllPatern(n, all):
    numbers = []
    all = []
    for i in range(n):
        numbers.append(i+1)
    for i in itertools.permutations(numbers):
        all.append(list(i))

    return all


def WhichNumber(p, q, all):
    val_p = 0
    val_q = 0
    for i in range(len(all)):
        val_p += 1
        if p == all[i]:
            break
    for i in range(len(all)):
        val_q += 1
        if q == all[i]:
            break

    return val_p, val_q

def main():
    n = int(input())
    p = [int(i) for i in input().split()]
    q = [int(i) for i in input().split()]
    all_numbers=[]

    all_numbers = AllPatern(n, all_numbers)
    val_p, val_q = WhichNumber(p, q, all)
    print(abs(val_p - val_q))



if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import itertools
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
p = [i-1 for i in p]
q = [i - 1 for i in q]
permutations_lis = itertools.permutations(range(n))# 全ての場合のリストを生成
dis_list = []
for i,case in enumerate(permutations_lis):
    if list(case) == p :
        a = i 
    elif list(case) == q :
        b = i
print(abs(a-b))

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n=ii()

p=limss()
q=limss()

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

pans=0
qans=0
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n=ii()

p=limss()
q=limss()

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

pans=0
qans=0
if p==q:
    print(0)
    exit()
for i,j in enumerate(range(factorial(n))):

    if "".join(p)=="".join(list(map(str,arr[i]))):
        pans=j
    elif "".join(q)=="".join(list(map(str,arr[i]))):
        qans=j
    
print(abs(pans-qans))

for i,j in enumerate(range(factorial(n))):

    if "".join(p)=="".join(list(map(str,arr[i]))):
        pans=j
    elif "".join(q)=="".join(list(map(str,arr[i]))):
        qans=j
    
print(abs(pans-qans))

Submission status: Runtime Error

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

from itertools import permutations

lst = permutations(range(1,n+1))
lst.sort()
print(abs(lst.index(P) - lst.index(Q)))

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
n = int(input())
a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))
x, y = 0, 0
perm = list(permutations(list(range(1, n+1))))
# print(perm)
for i in perm:
    if i == a:
        x = perm.index(i)
    if i == b:
        y = perm.index(i)
print(abs(x-y))

Submission status: Runtime Error

Solution code:
import itertools

if __name__ == '__main__':

	n = int(input())

	A = tuple(map(int,input().split()))
	B = tuple(map(int,input().split()))

    C  = [i for i in range(1,n+1)]
	D = [v for v in itertools.permutations(C, n)]

	a = D.index(A)
	b = D.index(B)

	print(abs(a-b))

Submission status: Runtime Error

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

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
import itertools
N = int(input())
P = list(map(int, input()))
Q = list(map(int, input()))
Ns = list(itertools.permutations(range(1,N+1), N))
NP = 0
NQ = 0
for ni in Ns:
  if ni < P:
    NP += 1
  if ni < Q:
    NQ += 1
print(abs(NP - NQ)

Submission status: Runtime Error

Solution code:
import itertools
import math
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
sample=[]
for i in range(1,n+1):
    sample.append(i)
perm=list(itertools.permutations(sample))
for i in range(math.factorial(n)):
    perm[i]=list(perm[i])
ans=[]
for i in range(math.factorial(n)):
    if list(perm[i]) == p or list(perm[i]) == q :
        ans.append(i+1)
        if len(ans) == 2:
            break

print(abs(ans[1]-ans[0]))

Submission status: Runtime Error

Solution code:
import numpy as np
import interpools

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

Num = range(1,N+1)

Number = str(''.join(map(str,Num)))


per_num=list(itertools.permutations(Number))
pernum_arr = np.ones(len(per_num))
for i in range(len(per_num)): 
    pernum_arr[i] = int(''.join(map(str,per_num[i])))
P = int(''.join(map(str,P)))
Q = int(''.join(map(str,Q)))
print(P)
ans = abs(np.where(pernum_arr==P)[0]-np.where(pernum_arr==Q)[0])
print(ans[0])

Submission status: Runtime Error

Solution code:
n=int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
import math
r=sorted(p)
t=0
l=0
s=0
for i in range(n):
    if p[i]>q[i]:
        l=p
        s=q
        break
    elif q[i]>p[i]:
        l=q
        s=p
        break
else:
    l=p
    s=q
for i in range(n):
    if l[i]>=s[i]:
        t=t+(r.index(l[i])-r.index(s[i])-1)*math.factorial(n-i-1)
    else:
        t=t+(n-r.index(s[i])-1+r.index(l[i])-1)*math.factrial(n-i-1)

print(t)

Submission status: Runtime Error

Solution code:
import sys
import itertools

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

l = list(itertools.permutations([i for i in range(1, n+1)], 3))
x = sorted([l.index(p)+1, l.index(q)+1], reverse=True)
print(x[0] - x[1])

Submission status: Runtime Error

Solution code:
import itertools 
n = int(input())
P = tuple(map(int, input().split()))
Q = tuple(map(int, input().split()))
l = list(itertools.permutation([i for i in range(1, n+1)]))
print(abs(l.index(P) - l.index(Q)))

Submission status: Runtime Error

Solution code:
import copy

def dic_num(N, s):
    factorial = 1
    cnt = 0
    ss = [0] * N
    for i in range(1, N+1):
        ss[i-1] = i
    
    for i in range(2, N+1):
        factorial *= i
        
    for reN in reversed(range(2, N+1)):
        factorial //= reN
        cnt += (ss.index(s[0]) - ss.index(min(s))) * factorial + 1
        ss.pop(0)
        s.pop(0)
        
        print("{} {}".format(reN, cnt))
    print(cnt)
    return cnt
    

def main():
    N = int(input())
    p_n = list(map(int, input().split()))
    q_n = list(map(int, input().split()))
    
    print(abs(dic_num(N, p_n) - dic_num(N, q_n)))

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import itertools
N=int(input())
P=list(map(int,input().split()))
Q=list(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: Runtime Error

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

Submission status: Runtime Error

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

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

def g(a):
    if a == []:
        return(1)
    else:
        b = sorted(a)
        for i in range(0,len(a)):
            if a[0] == b[i]:
                a.pop(0)
                return(i * f(len(a)) + g(a))

print(abs(g(P)-g(Q)))

Submission status: Runtime Error

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

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

def g(a):
    if a == []:
        return(1)
    else:
        b = sorted(a)
        for i in range(0,len(a)):
            if a[0] == b[i]:
                a.pop(0)
                return(i * f(len(a)) * g(a))

print(abs(g(P)-g(Q)))

Submission status: Runtime Error

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

li = list(itertools.permutations(P,N))
li.sort()

a = 0
b = 0

for i in range(math.factorial(N)):
    if li[i] == P:
        a = i
    elif li[i] == Q:
        b = i
    else:
        a = a
        b = b
        
print(abs(a-b))

Submission status: Runtime Error

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

li = list(itertools.permutations(P ,N))

a = 0
b = 0

for i in range(math.factorial(N)):
    if li[i] == P:
        a = i
    elif li[i] == Q:
        b = i
    else:
        a = a
        b = b
        
print(abs(a-b))

Submission status: Runtime Error

Solution code:
#C - Count Order
N = int(input())
P = tuple(map(int,input().split()))
Q = tuple(map(int,input().split()))

li = list(itertools.permutations(P ,N))

a = 0
b = 0

for i in range(math.factorial(3)):
    if li[i] == P:
        a = i
    elif li[i] == Q:
        b = i
    else:
        a = a
        b = b
        
print(abs(a-b))

Submission status: Runtime Error

Solution code:
import itertools

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

N_list = [i for i in range(1,N)]
conbination = list(itertools.permutations(N_list, N))

a = conbination.index(tuple(P))
b = conbination.index(tuple(Q))

print(abs(a-b))

Submission status: Runtime Error

Solution code:
import itertools

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

N_list = [i for i in range(1,N)]
conbination = list(itertools.permutations(N_list, 8))

a = conbination.index(tuple(P))
b = conbination.index(tuple(Q))

print(abs(a-b))

Submission status: Runtime Error

Solution code:
import itertools

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

N_list = [1, 2, 3, 4, 5, 6, 7, 8]
conbination = list(itertools.permutations(N_list, 8))

a = conbination.index(tuple(P))
b = conbination.index(tuple(Q))

print(abs(a-b))

Submission status: Runtime Error

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

import itertools
 
n_list = [i+1 for i in range(N)]
all_list = list(itertools.permutations(A))
a = all_list.index(P)
b = all_list.index(Q)
print(abs(a - b))

Submission status: Runtime Error

Solution code:
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
lis1 = [i for i in range(1,N+1)]
lis2 = [i for i in range(1,N+1)]
def number(a, lis):
  total_order = 1
  for i in range(N):
    tmp_order = lis.index(a[i])
    lis.remove(a[i])
    total_order += tmp_order * math.factorial(len(lis))
  return total_order
print(abs(number(P, lis1) - number(Q, lis2)))

Submission status: Runtime Error

Solution code:
import math
N = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
lis1 = [i for i in range(1,N+1)]
lis2 = [i for i in range(1,N+1)]
def number(a, lis):
  total_order = 1
  for i in range(N):
    tmp_order = lis.index(a[i])
    lis.pop(a[i])
    total_order += tmp_order * math.factorial(len(lis))
  return total_order
print(abs(number(P, lis1) - number(Q, lis2)))

Submission status: Runtime Error

Solution code:
<?php
//https://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        // もう取り出すものがなければその時点の$permsが順列の一つなのでそのまま返却 
        $return = array($perms);
    } else {
        $return = array();
        // 並んでる数字を順番にみてく
        for ($i =  0; $i < count($items); $i++) {
            // 処理対象の配列と、組み合わせを保持してる変数を別変数にコピー
            // array_spliceなどは破壊的なメソッドなので退避しないと元配列が変更される
            $newitems = $items;
            $newperms = $perms;
            // インデックスが$iの値を$fooにとる。($newitemsからは削除される)
            list($foo) = array_splice($newitems, $i, 1);
            // 取り除いた値（$foo)を組み合わせの候補の先頭に持ってくる
            array_unshift($newperms, $foo);
            // 最終的に呼び出し元に返却する配列に追加する
            // 追加する配列は、一文字削ったあとの$newitems,
            // 現段階での組み合わせの$newpermsを引数に、再帰的に自分を呼び出した結果
            $return = array_merge($return, pc_permute($newitems, $newperms));
        }
    }
    return $return;
}

// ----------------------------------------------------
// こっから実際に解く
// ----------------------------------------------------

// 入力値の取得（int変換)
$N = intval(trim(fgets(STDIN)));
// 入力値の取得（配列化）
$P = explode(" ",trim(fgets(STDIN));
$Q = explode(" ",trim(fgets(STDIN));

// 順列の生成
$a = range(1,$N);
// $permutated = pc_permute($a);
// sort($permutated);
// 
// $p_index = -1;
// $q_index = -1;
// 
// // 列挙した順列をfor文で確認していき、PとQの位置を確認する
// for ($i=0; $i < count($permutated); $i++){
//   if ($permutated[$i] == $P){
//     $p_index = $i;
//   }
//   if ($permutated[$i] == $Q){
//     $q_index = $i;
//   }
// }
// 
// // 答えの計算
// $ans = abs($p_index - $q_index);
// printf("%d\n",$ans);

Submission status: Runtime Error

Solution code:
<?php
//https://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        // もう取り出すものがなければその時点の$permsが順列の一つなのでそのまま返却 
        $return = array($perms);
    } else {
        $return = array();
        // 並んでる数字を順番にみてく
        for ($i =  0; $i < count($items); $i++) {
            // 処理対象の配列と、組み合わせを保持してる変数を別変数にコピー
            // array_spliceなどは破壊的なメソッドなので退避しないと元配列が変更される
            $newitems = $items;
            $newperms = $perms;
            // インデックスが$iの値を$fooにとる。($newitemsからは削除される)
            list($foo) = array_splice($newitems, $i, 1);
            // 取り除いた値（$foo)を組み合わせの候補の先頭に持ってくる
            array_unshift($newperms, $foo);
            // 最終的に呼び出し元に返却する配列に追加する
            // 追加する配列は、一文字削ったあとの$newitems,
            // 現段階での組み合わせの$newpermsを引数に、再帰的に自分を呼び出した結果
            $return = array_merge($return, pc_permute($newitems, $newperms));
        }
    }
    return $return;
}

// ----------------------------------------------------
// こっから実際に解く
// ----------------------------------------------------

// 入力値の取得（int変換)
$N = intval(trim(fgets(STDIN)));
// 入力値の取得（配列化）
$P = explode(" ",trim(fgets(STDIN));
$Q = explode(" ",trim(fgets(STDIN));

// 順列の生成
$a = range(1,$N);
$permutated = pc_permute($a);
sort($permutated);

$p_index = -1;
$q_index = -1;

// 列挙した順列をfor文で確認していき、PとQの位置を確認する
for ($i=0; $i < count($permutated); $i++){
  if ($permutated[$i] == $P){
    $p_index = $i;
  }
  if ($permutated[$i] == $Q){
    $q_index = $i;
  }
}

// 答えの計算
$ans = abs($p_index - $q_index);
printf("%d\n",$ans);

Submission status: Runtime Error

Solution code:
<?php

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        $return = array($perms);
    } else {
        $return = array();
        for ($i =  0; $i < count($items); $i++) {
            $newitems = $items;
            $newperms = $perms;
            list($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, $foo);
            $return = array_merge($return, pc_permute($newitems, $newperms));
        }
    }
    return $return;
}

$N = intval(trim(fgets(STDIN)));
$P = explode(" ",fgets(STDIN));
$Q = explode(" ",fgets(STDIN));

$a = range(1,$N);
$permutated = pc_permute($a);
sort($permutated);

$p_index = -1;
$q_index = -1;

for ($i=0; $i < count($permutated); $i++){
  if ($permutated[$i] == $P){
    $p_index = $i;
  }
  if ($permutated[$i] == $Q){
    $q_index = $i;
  }
}

$ans = abs($p_index - $q_index);
printf("%d\n",$ans);

Submission status: Runtime Error

Solution code:
<?php
//https://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        // もう取り出すものがなければその時点の$permsが順列の一つなのでそのまま返却 
        $return = array($perms);
    } else {
        $return = array();
        // 並んでる数字を順番にみてく
        for ($i =  0; $i < count($items); $i++) {
            // 処理対象の配列と、組み合わせを保持してる変数を別変数にコピー
            // array_spliceなどは破壊的なメソッドなので退避しないと元配列が変更される
            $newitems = $items;
            $newperms = $perms;
            // インデックスが$iの値を$fooにとる。($newitemsからは削除される)
            list($foo) = array_splice($newitems, $i, 1);
            // 取り除いた値（$foo)を組み合わせの候補の先頭に持ってくる
            array_unshift($newperms, $foo);
            // 最終的に呼び出し元に返却する配列に追加する
            // 追加する配列は、一文字削ったあとの$newitems,
            // 現段階での組み合わせの$newpermsを引数に、再帰的に自分を呼び出した結果
            $return = array_merge($return, pc_permute($newitems, $newperms));
        }
    }
    return $return;
}

// ----------------------------------------------------
// こっから実際に解く
// ----------------------------------------------------

// 入力値の取得（int変換)
$N = intval(trim(fgets(STDIN)));
// 入力値の取得（配列化）
$P = explode(" ",fgets(STDIN));
$Q = explode(" ",fgets(STDIN));

// 順列の生成
$a = range(1,$N);
$permutated = pc_permute($a);
sort($permutated);

$p_index = -1;
$q_index = -1;

// 列挙した順列をfor文で確認していき、PとQの位置を確認する
for ($i=0; $i < count($permutated); $i++){
  if ($permutated[$i] == $P){
    $p_index = $i;
  }
  if ($permutated[$i] == $Q){
    $q_index = $i;
  }
}

// 答えの計算
$ans = abs($p_index - $q_index);
printf("%d\n",$ans);

Submission status: Runtime Error

Solution code:
<?php
//https://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        // もう取り出すものがなければその時点の$permsが順列の一つなのでそのまま返却 
        $return = array($perms);
    } else {
        $return = array();
        // 並んでる数字を順番にみてく
        for ($i =  0; $i < count($items); $i++) {
            // 処理対象の配列と、組み合わせを保持してる変数を別変数にコピー
            // array_spliceなどは破壊的なメソッドなので退避しないと元配列が変更される
            $newitems = $items;
            $newperms = $perms;
            // インデックスが$iの値を$fooにとる。($newitemsからは削除される)
            list($foo) = array_splice($newitems, $i, 1);
            // 取り除いた値（$foo)を組み合わせの候補の先頭に持ってくる
            array_unshift($newperms, $foo);
            // 最終的に呼び出し元に返却する配列に追加する
            // 追加する配列は、一文字削ったあとの$newitems,
            // 現段階での組み合わせの$newpermsを引数に、再帰的に自分を呼び出した結果
            $return = array_merge($return, pc_permute($newitems, $newperms));
        }
    }
    return $return;
}

// ----------------------------------------------------
// こっから実際に解く
// ----------------------------------------------------

// 入力値の取得（int変換)
$N = intval(trim(fgets(STDIN)));
// 入力値の取得（配列化）
$P = explode(" ",fgets(STDIN));
$Q = explode(" ",fgets(STDIN));

// 順列の生成
$a = range(1,$N);
$perms = pc_permute($a);
sort($perms);

$p_index = -1;
$q_index = -1;

// 列挙した順列をfor文で確認していき、PとQの位置を確認する
for ($i=0; $i < count($perms); $i++){
  if ($perms[$i] == $P){
    $p_index = $i;
  }
  if ($perms[$i] == $Q){
    $q_index = $i;
  }
}

// 答えの計算
$ans = abs($p_index - $q_index);
printf("%d\n",$ans);

Submission status: Runtime Error

Solution code:
<?php
function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        $return = array($perms);
    } else {
        $return = array();
        for ($i =  0; $i < count($items); $i++) {
            $newitems = $items;
            $newperms = $perms;
            list($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, $foo);
            $return = array_merge($return, pc_permute($newitems, $newperms));
        }
    }
    return $return;
}
$N = intval(trim(fgets(STDIN)));
$P = explode(" ",fgets(STDIN));
$Q = explode(" ",fgets(STDIN));

$a = range(1,$N);
$perms = pc_permute($a);
sort($perms);

$p_index = -1;
$q_index = -1;

for ($i=0; $i < count($perms); $i++){
  if ($perms[$i] == $P){
    $p_index = $i;
  }
  if ($perms[$i] == $Q){
    $q_index = $i;
  }
}

$ans = abs($p_index - $q_index);
echo $ans;

Submission status: Runtime Error

Solution code:
<?php
//https://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        // もう取り出すものがなければその時点の$permsが順列の一つなのでそのまま返却 
        $return = array($perms);
    } else {
        $return = array();
        // 並んでる数字を順番にみてく
        for ($i =  0; $i < count($items); $i++) {
            // 処理対象の配列と、組み合わせを保持してる変数を別変数にコピー
            // array_spliceなどは破壊的なメソッドなので退避しないと元配列が変更される
            $newitems = $items;
            $newperms = $perms;
            // インデックスが$iの値を$fooにとる。($newitemsからは削除される)
            list($foo) = array_splice($newitems, $i, 1);
            // 取り除いた値（$foo)を組み合わせの候補の先頭に持ってくる
            array_unshift($newperms, $foo);
            // 最終的に呼び出し元に返却する配列に追加する
            // 追加する配列は、一文字削ったあとの$newitems,
            // 現段階での組み合わせの$newpermsを引数に、再帰的に自分を呼び出した結果
            $return = array_merge($return, pc_permute($newitems, $newperms));
        }
    }
    return $return;
}


// ----------------------------------------------------
// こっから実際に解く
// ----------------------------------------------------

// 入力値の取得（int変換)
$N = intval(trim(fgets(STDIN)));
// 入力値の取得（配列化）
$P = explode(" ",fgets(STDIN));
$Q = explode(" ",fgets(STDIN));

// 順列の生成
$a = range(1,$N);
$perms = pc_permute($a);
sort($perms);

$p_index = -1;
$q_index = -1;

// 列挙した順列をfor文で確認していき、PとQの位置を確認する
for ($i=0; $i < count($perms); $i++){
  if ($perms[$i] == $P){
    $p_index = $i;
  }
  if ($perms[$i] == $Q){
    $q_index = $i;
  }
}

// 答えの計算
$ans = abs($p_index - $q_index);
echo $ans;

Submission status: Runtime Error

Solution code:
<?php
//https://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        // もう取り出すものがなければその時点の$permsが順列の一つなのでそのまま返却 
        $return = array($perms);
    } else {
        $return = array();
        // 並んでる数字を順番にみてく
        for ($i =  0; $i < count($items); $i++) {
            // 処理対象の配列と、組み合わせを保持してる変数を別変数にコピー
            // array_spliceなどは破壊的なメソッドなので退避しないと元配列が変更される
            $newitems = $items;
            $newperms = $perms;
            // インデックスが$iの値を$fooにとる。($newitemsからは削除される)
            list($foo) = array_splice($newitems, $i, 1);
            // 取り除いた値（$foo)を組み合わせの候補の先頭に持ってくる
            array_unshift($newperms, $foo);
            // 最終的に呼び出し元に返却する配列に追加する
            // 追加する配列は、一文字削ったあとの$newitems,
            // 現段階での組み合わせの$newpermsを引数に、再帰的に自分を呼び出した結果
            $return = array_merge($return, pc_permute($newitems, $newperms));
        }
    }
    return $return;
}


// ----------------------------------------------------
// こっから実際に解く
// ----------------------------------------------------

// 入力値の取得（int変換)
$N = intval(trim(fgets(STDIN)));
// 入力値の取得（配列化）
$P = explode(" ",fgets(STDIN));
$Q = explode(" ",fgets(STDIN));

// 順列の生成
$a = range(1,$N);
$perms = pc_permute($a);
sort($perms);

$p_index = -1;
$q_index = -1;

// 列挙した順列をfor文で確認していき、PとQの位置を確認する
for ($i=0; $i < count($perms); $i++){
  if ($perms[$i] == $P){
    $p_index = $i;
  }
  if ($perms[$i] == $Q){
    $q_index = $i;
  }
}

// 答えの計算
$ans = abs($p_index - $q_index);
echo $ans;

?>

Submission status: Runtime Error

Solution code:
 N = int(input())

def factorial(num):
    if num == 1:
        return 1
    return num * factorial(num - 1)

def count_order(group):
    numbers = [i for i in range(1, N + 1)]
    res = 1
    for i in range(len(group) - 1):
        num = group[i]
        res += numbers.index(num) * pattern[-(i + 1)]
        numbers.pop(numbers.index(num))
    return res


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

pattern = [factorial(i) for i in range(1, N)]
res_p = count_order(P)
res_q = count_order(Q)

print(abs(res_p - res_q))

Submission status: Runtime Error

Solution code:
import itertools

n = int(input())
p = input().replace(" ", "")
q = input().replace(" ", "")
m = ""
for i in range(1, n + 1):
    m += str(i)
anagram_list = ["".join(v) for v in itertools.permutations(m)]

pa = 0
qa = 0

for i in range(len(anagram_list)):
    if anagram_list[i] == p:
        pa = i+1
    if anagram_list[i] == q:
        qa = i+1a
print(abs(pa-qa))

Submission status: Runtime Error

Solution code:
import itertools
n = int(input())
p =[int(i) for i in input().split()]
q =[int(i) for i in input().split()]
a = 0
b = 0
cnt = 0
p1= p.copy()
p1.sort()
n_list = list(itertools.permutations(p1))
for i in n_list:
    if list(i)==p:
        a = cnt +1
    if list(i)==q:
        b = cnt +1
    cnt += 1
        
print(abs(a-b))

Submission status: Runtime Error

Solution code:
import itertools
n = int(input())
p =[int(i) for i in input().split()]
q =[int(i) for i in input().split()]
a = 0
b = 0
cnt = 0
p1= p.copy()
p1.sort()
n_list = list(itertools.permutations(p1))
for i in n_list:
    if list(i)==p:
        a = cnt +1
    elif list(i)==q:
        b = cnt +1
    cnt += 1
        
print(abs(a-b))

Submission status: Runtime Error

Solution code:
import itertools
n = int(input())
p =[int(i) for i in input().split()]
q =[int(i) for i in input().split()]
a = 0
b = 0
cnt = 0

n_list = list(itertools.permutations(p1))
for i in n_list:
    if list(i)==p:
        a = cnt +1
    elif list(i)==q:
        b = cnt +1
    cnt += 1
        
print(abs(a-b))