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)

#[allow(unused_imports)]
use std::cmp::{Ordering};

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};

#[allow(unused_imports)]
use std::iter::FromIterator;

#[allow(unused_macros)]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::min($x, min!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::max($x, max!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! get { 
    ([$t: ty]) => { 
        { 
            let mut line = String::new(); 
            stdin().read_line(&mut line).unwrap(); 
            line.split_whitespace().map(|t|t.parse::<$t>().unwrap()).collect::<Vec<_>>()
        }
    };
    ([$t: ty];$n: expr) => {
        (0..$n).map(|_|get!([$t])).collect::<Vec<_>>()
    };
    ($t: ty) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t: ty),*) => {
        { 
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*)
        }
    };
    ($t: ty; $n: expr) => {
        (0..$n).map(|_|get!($t)).collect::<Vec<_>>()
    };
    ($($t: ty),*; $n: expr) => {
        (0..$n).map(|_|get!($($t),*)).collect::<Vec<_>>()
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*).unwrap();
    }
}

const BIG_STACK_SIZE: bool = true;

#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}

#[derive(Clone)]
pub struct ElementSwaps {
    sdir: Vec<SizeDirection>,
    emit_reset: bool,
    swaps_made: usize,
}
impl ElementSwaps {
    pub fn new(length: usize) -> ElementSwaps {
        ElementSwaps {
            emit_reset: true,
            sdir: (0..length)
                .map(|i| SizeDirection {
                    size: i,
                    dir: Direction::Neg,
                })
            .collect(),
            swaps_made: 0,
        }
    }
}
#[derive(Copy, Clone)]
enum Direction {
    Pos,
    Neg,
}
#[derive(Copy, Clone)]
struct SizeDirection {
    size: usize,
    dir: Direction,
}
impl Iterator for ElementSwaps {
    type Item = (usize, usize);
    fn next(&mut self) -> Option<(usize, usize)> {
        fn new_pos_wrapping(i: usize, s: Direction) -> usize {
            i.wrapping_add(match s {
                Direction::Pos => 1,
                Direction::Neg => !0,
            })
        }
        fn new_pos(i: usize, s: Direction) -> usize {
            match s {
                Direction::Pos => i + 1,
                Direction::Neg => i - 1,
            }
        }
        let max = self
            .sdir
            .iter()
            .cloned()
            .enumerate()
            .filter(|&(i, sd)| {
                new_pos_wrapping(i, sd.dir) < self.sdir.len()
                    && self.sdir[new_pos(i, sd.dir)].size < sd.size
            })
        .max_by(|&(_, sd1), &(_, sd2)| sd1.size.cmp(&sd2.size));
    match max {
        Some((i, sd)) => {
            let j = new_pos(i, sd.dir);
            self.sdir.swap(i, j);
            for x in &mut self.sdir {
                if x.size > sd.size {
                    x.dir = match x.dir {
                        Direction::Pos => Direction::Neg,
                        Direction::Neg => Direction::Pos,
                    };
                }
            }
            self.swaps_made += 1;
            Some((i, j))
        }
        None => {
            if self.emit_reset {
                self.emit_reset = false;
                if self.sdir.len() > 1 {
                    self.swaps_made += 1;
                    Some((0, 1))
                } else {
                    self.swaps_made += 1;
                    Some((0, 0))
                }
            } else {
                None
            }
        }
    }
    }
#[inline]
#[allow(dead_code)]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let n: usize = (2..self.sdir.len() + 1).product();
        (n - self.swaps_made, Some(n - self.swaps_made))
    }
}
pub struct Permutations<T> {
    swaps: ElementSwaps,
    v: Vec<T>,
}
impl<T: Clone> Permutations<T> {
    pub fn new(v: Vec<T>) -> Self {
        Permutations {
            swaps: ElementSwaps::new(v.len()),
            v: v,
        }
    }
}
impl<T: Clone> Iterator for Permutations<T> {
    type Item = Vec<T>;
#[inline]
    fn next(&mut self) -> Option<Vec<T>> {
        match self.swaps.next() {
            None => None,
            Some((0, 0)) => Some(self.v.clone()),
            Some((a, b)) => {
                let elt = self.v.clone();
                self.v.swap(a, b);
                Some(elt)
            }
        }
    }
#[inline]
#[allow(dead_code)]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.swaps.size_hint()
    }
}

fn solve() {
    let n = get!(usize);
    let p = get!([usize]).into_iter().fold(String::new(), |s, e| s + &e.to_string());
    let q = get!([usize]).into_iter().fold(String::new(), |s, e| s + &e.to_string());

    let mut p_count: isize = 0;
    let mut q_count: isize = 0;

    let perm = Permutations::new((0..n).collect::<Vec<_>>());
    for vec in perm {
        let mut s = String::new();
        for e in vec {
            s += &(e+1).to_string();
        }
        if s > p {
            p_count += 1;
        } 
        if s > q {
            q_count += 1;
        }
    }
    println!("{}", (p_count-q_count).abs());
}