Problem:
Score : 700 points

Problem Statement

We have N cards numbered 1, 2, ..., N.
Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side.
Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up.

Determine whether it is possible to have a non-decreasing sequence facing up from left to right (that is, for each i (1 \leq i \leq N - 1), the integer facing up on the (i+1)-th card from the left is not less than the integer facing up on the i-th card from the left) by repeating the operation below. If the answer is yes, find the minimum number of operations required to achieve it.

Choose an integer i (1 \leq i \leq N - 1).
Swap the i-th and (i+1)-th cards from the left, then flip these two cards.

Constraints

1 \leq N \leq 18

1 \leq A_i, B_i \leq 50 (1 \leq i \leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If it is impossible to have a non-decreasing sequence, print -1.
If it is possible, print the minimum number of operations required to achieve it.

Sample Input 1

3
3 4 3
3 2 3

Sample Output 1

1

By doing the operation once with i = 1, we have a sequence [2, 3, 3] facing up, which is non-decreasing.

Sample Input 2

2
2 1
1 2

Sample Output 2

-1

After any number of operations, we have the sequence [2, 1] facing up, which is not non-decreasing.

Sample Input 3

4
1 2 3 4
5 6 7 8

Sample Output 3

0

No operation may be required.

Sample Input 4

5
28 15 22 43 31
20 22 43 33 32

Sample Output 4

-1

Sample Input 5

5
4 46 6 38 43
33 15 18 27 37

Sample Output 5

3

Solution in Rust (1.15.1) (judge verdict: Time Limit Exceeded)

#[allow(dead_code)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(dead_code)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

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

#[allow(dead_code)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

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

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

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

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

macro_rules! order_by {
    ($($x:tt)*) => {
        |l, r| {
            order_by_inner!(l, r, $($x)*)
        }
    }
}
macro_rules! order_by_inner {
    () => {};
    ($l:ident) => {std::cmp::Ordering::Equal};
    ($l:ident , ) => {std::cmp::Ordering::Equal};
    ($l:ident , $r:ident) => {std::cmp::Ordering::Equal};
    ($l:ident , $r:ident , ) => {std::cmp::Ordering::Equal};

    // last
    ($l:ident , $r:ident , $x:tt asc) => {
        $l.$x.cmp(&$r.$x)
    };
    ($l:ident , $r:ident , $x:tt desc) => {
        $l.$x.cmp(&$r.$x).reverse()
    };
    ($l:ident , $r:ident , $x:tt) => {
        order_by_inner!($l, $r, $x asc)
    };

    // mid
    ($l:ident , $r:ident , $x:tt asc , $($p:tt)+) => {
        match $l.$x.cmp(&$r.$x) {
            std::cmp::Ordering::Equal => {
                order_by_inner!($l, $r, $($p)+)
            },
            other => other
        }
    };
    ($l:ident , $r:ident , $x:tt desc , $($p:tt)+) => {
        match $l.$x.cmp(&$r.$x).reverse() {
            std::cmp::Ordering::Equal => {
                order_by_inner!($l, $r, $($p)+)
            },
            other => other
        }
    };
    ($l:ident , $r:ident , $x:tt , $($p:tt)+) => {
        order_by_inner!($l, $r, $x asc, $($p)+)
    };
}

fn main() {
    input! {
        n: usize,
        aa: [usize; n],
        bb: [usize; n],
    }
    // n <= 18

    let mut ll = aa.into_iter().enumerate().map(|(i, v)| (i + 1, 0 as usize, v)).collect::<Vec<_>>();
    ll.append(&mut {
        bb.into_iter().enumerate().map(|(i, v)| (i + 1, 1 as usize, v)).collect::<Vec<_>>()
    });

    let ans = get(&ll);
    if ans.len() > 0 {
        let k = ans.into_iter().map(|ans_i| {
            let mut indices = ans_i.iter().map(|a| a.0).collect::<Vec<_>>();
            let mut cnt = 0;
            let mut last_change = indices.len() - 1;
            while last_change > 1 {
                let mut tmp = 0;
                for i in 0..last_change {
                    if indices[i] > indices[i + 1] {
                        cnt += 1;
                        indices.swap(i, i + 1);
                        tmp = i + 1;
                    }
                }
                last_change = tmp;
            }
            cnt
        }).min().unwrap();
        println!("{}", k);
    } else {
        println!("-1");
    }
}

fn get(v: &Vec<(usize, usize, usize)>) -> Vec<Vec<(usize, usize, usize)>> {
    let mut v = v.clone();
    v.sort_by(order_by!(2, 0, 1));
    // println!("{:?}", v);
    let mut r = vec![(0,0, 0)];
    let mut result = vec![];
    let mut used = vec![];
    get_i(&v, &mut r, &mut used, 0, &mut result);
    result
}

fn get_i(v: &Vec<(usize, usize, usize)>, result: &mut Vec<(usize, usize, usize)>, used: &mut Vec<usize>, i: usize, final_result: &mut Vec<Vec<(usize, usize, usize)>>) {
    // println!("then get_i[{}], result: {:?}, used: {:?}", i, result, used);
    if i >= v.len() / 2 {
        if result.iter().filter(|a| a.1 == 1).count() % 2 == 0 {
            final_result.push(result.clone());
        }
        return;
    }
    let last = result[result.len() - 1].2;
    for &(index, ab, value) in v {
        if used.contains(&index) {
            // println!("  value: ({}, {}, {})", index, ab, value);
            // println!("        contains");
            continue;
        }
        if value < last {
            // println!("  value: ({}, {}, {})", index, ab, value);
            // println!("        small");
            continue;
        }
        if (i % 2 == 0 && odd(index, ab)) || (i % 2 != 0 && !odd(index, ab))  {
            // println!("  value: ({}, {}, {})", index, ab, value);
            // println!("        use");
            result.push((index, ab, value));
            used.push(index);
            get_i(v, result, used, i + 1, final_result);
            used.pop();
            result.pop();
        }
    }
}


fn odd(index: usize, ab: usize) -> bool {
    match index % 2 == 0 {
        true => ab == 1,
        false => ab == 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn odd_test() {
        assert_eq!(odd(1, 0), true);
        assert_eq!(odd(2, 1), true);
        assert_eq!(odd(3, 0), true);
        assert_eq!(odd(4, 1), true);
        assert_eq!(odd(5, 0), true);

        assert_eq!(odd(1, 1), false);
        assert_eq!(odd(2, 0), false);
        assert_eq!(odd(3, 1), false);
        assert_eq!(odd(4, 0), false);
        assert_eq!(odd(5, 1), false);
    }
}