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 Rust (1.15.1) (judge verdict: Accepted)

use std::io;

fn main() {
    let n = parse_line::<usize>();
    let mut v1 = parse_values(n);
    let mut v2 = parse_values(n);

    let mut diffs: Vec<i64> = Vec::new();

    let max_len = v1.len();
    let factorial_cache = [5040, 720, 120, 24, 6, 2, 1];
    let f_cache = &factorial_cache[(8 - max_len)..];
    //println!("{:?}", f_cache);
    for i in 0..max_len - 1 {
        let t = process_head(&mut v1, &mut v2);
        diffs.push(t.0);
        v1 = t.1;
        v2 = t.2;
        //println!("{:?}", v1);
    }
    //println!("{:?}", diffs);
    let mut sum = 0;
    for i in 0..diffs.len() {
        //println!("{:?}", diffs[i]);
        //println!("{:?}", f_cache[i]);
        sum += diffs[i] * f_cache[i] * (-1);
    }
    if sum > 0 {
        println!("{:?}", sum);
    } else {
        println!("{:?}", -sum);
    }
}

fn parse_line<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn parse_values<T: std::str::FromStr>(n: usize) -> Vec<T> {
    let line = parse_line::<String>();
    let mut split = line.split_whitespace();
    let mut values = Vec::with_capacity(n);
    for _ in 0..n {
        let v = split.next().unwrap().parse::<T>().ok().unwrap();
        values.push(v);
    }
    values
}

fn process_head(v1: &mut Vec<i64>, v2: &mut Vec<i64>) -> (i64, Vec<i64>, Vec<i64>) {
    let v1_head = v1[0];
    let v1_tail = &v1[1..];

    let v2_head = v2[0];
    let v2_tail = &v2[1..];
    let diff = v1[0] - v2[0];

    let v1_after: Vec<i64> = v1_tail
        .iter()
        .map(|&i| if i > v1_head { i - 1 } else { i })
        .collect();
    let v2_after: Vec<i64> = v2_tail
        .iter()
        .map(|&i| if i > v2_head { i - 1 } else { i })
        .collect();
    (diff, v1_after, v2_after)
}