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)

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// use std::io::{stdout, Write, BufWriter};
use std::cmp::{max, min};

// use std::thread;
// use std::time::Duration;

fn main() {
    input! {
        n: usize,
        p: [usize; n],
        q: [usize; n],
    }

    let mut f = Facto::new(n - 1).unwrap();
    let (a, b) = (lex_order(&p, &mut f, n), lex_order(&q, &mut f, n));
    println!("{}", max(a, b) - min(a, b));
}

type SomeInt = usize;

struct Facto {
    cache: Vec<SomeInt>,
}

impl Facto {
    fn facto(n: SomeInt) -> Option<SomeInt> {
        if 1 <= n {
            Some(
                (1..(n + 1)).product()
            )
        } else if n == 0 || n == 1 { Some(1) }
        else { None }
    }

    fn new(n: SomeInt) -> Option<Facto> {
        if 0 <= n {
            Some(Facto{
                cache: (0..(n + 1)).scan(1, |state, i| {
                    if i == 0 { *state = 1; }
                    else { *state *= i; }
                    Some(*state)
                }).collect()
            })
        } else { None }
    }

    fn facto_cached(&mut self, n: SomeInt) -> Option<SomeInt> {
        if n < 0 { return None }
        let l = self.cache.len() as SomeInt;
        let mut to_be_appended = (l..(n + 1))
            .scan(*((self.cache).last().unwrap()), |state, i| {
                *state *= i;
                 Some(*state)
            }).collect();
        self.cache.append(&mut to_be_appended);
        Some(*(self.cache.get(n as usize).unwrap()))
    }
}



// {1, ..., n}からなる順列の辞書式順序を求める
fn lex_order(v: &[SomeInt], f: &mut Facto, n: usize) -> SomeInt {
    let mut states: Vec<SomeInt> = vec![1; n];
    let sum: SomeInt = v.iter().enumerate().map(|(i, &x)| {
        states[x - 1] = 0;
        let s: SomeInt = states.iter().take(x).sum();
        s  * f.facto_cached(n - i - 1).unwrap()
    }).sum();
    sum + 1
}