//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let 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 $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::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, bytes) => { read_value!($iter, String).bytes().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } fn naive(a: &[T], b: &[T]) -> usize { let mut map = std::collections::BTreeMap::new(); for (i, b) in b.iter().enumerate() { map.entry(b).or_insert(vec![]).push(i); } let mut x = vec![0; a.len()]; for (x, a) in x.iter_mut().zip(a.iter()).rev() { *x = map.get_mut(a).unwrap().pop().unwrap(); } let mut call = vec![(0, a.len(), false)]; let mut tmp = vec![]; let mut ans = 0; while let Some((l, r, merge)) = call.pop() { if r - l <= 1 { continue; } let m = (l + r) / 2; if merge { tmp.clear(); let mut i = l; let mut j = m; while i < m && j < r { if x[i] <= x[j] { tmp.push(x[i]); i += 1; } else { ans += m - i; tmp.push(x[j]); j += 1; } } tmp.extend_from_slice(&x[i..m]); x[l..j].copy_from_slice(&tmp); } else { call.push((l, r, true)); call.push((l, m, false)); call.push((m, r, false)); } } ans } fn run() { input! { n: usize, a: [usize; n], b: [usize; n], } let p = a.windows(2).map(|a| a[0] ^ a[1]).collect::>(); let q = b.windows(2).map(|a| a[0] ^ a[1]).collect::>(); let mut x = p.clone(); let mut y = q.clone(); x.sort(); y.sort(); if !(a[0] == b[0] && a[n - 1] == b[n - 1] && x == y) { println!("-1"); return; } let ans = naive(&p, &q); println!("{}", ans); } fn main() { run(); }