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

Solution in Go (1.6) (judge verdict: Accepted)

package main

import (
	"bufio"
	"fmt"
	"os"
	"reflect"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func init() {
	const maxWord = (1 << 30)
	buf := []byte{}
	sc.Buffer(buf, maxWord)
	sc.Split(bufio.ScanWords)
}

func input() string {
	sc.Scan()
	return sc.Text()
}

func makeFactorial(n int) int {
	result := 1
	for i := 2; i <= n; i++ {
		result *= i
	}
	return result
}

var patternNum = makeFactorial(8)
var patterns = make([][]int, 0, patternNum)

func remove(nums []int, i int) []int {
	result := make([]int, 0, len(nums)-1)
	result = append(result, nums[:i]...)
	result = append(result, nums[i+1:]...)
	return result
}

func permute(pat, nums []int) {
	if len(nums) == 0 {
		dst := make([]int, len(pat))
		copy(dst, pat)
		patterns = append(patterns, dst)
		return
	}

	for i := 0; i < len(nums); i++ {
		permute(append(pat, nums[i]), remove(nums, i))
	}
}

func calcRank(nums []int, patterns [][]int) int {
	result := 0
	for i := 0; i < len(patterns); i++ {
		if reflect.DeepEqual(patterns[i], nums) {
			result = i
			break
		}
	}
	return result
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	n, _ := strconv.Atoi(input())
	p := make([]int, n)
	q := make([]int, n)
	for i := 0; i < n; i++ {
		p[i], _ = strconv.Atoi(input())
	}
	for i := 0; i < n; i++ {
		q[i], _ = strconv.Atoi(input())
	}

	nums := make([]int, n)
	for i := 1; i <= n; i++ {
		nums[i-1] = i
	}
	permute([]int{}, nums)

	pRank := calcRank(p, patterns)
	qRank := calcRank(q, patterns)
	fmt.Println(abs(pRank - qRank))
}