// https://yukicoder.me/problems/no/1467 // これっぽい感が fn run() { input! { n: usize, m: usize, k: i64, b: [i64; n], r: [i64; m], } let mut map = std::collections::BTreeMap::new(); for &b in b.iter() { map.entry(b % k).or_insert(vec![vec![]; 2])[0].push(b / k); } for &r in r.iter() { map.entry(r % k).or_insert(vec![vec![]; 2])[1].push(r / k); } let mut sum = 0; let mut cnt = 0; let inf = std::i64::MAX / 10; for (_, mut p) in map { if p[0].len() > p[1].len() { p.swap(0, 1); } let mut a = vec![]; a.extend(p[0].iter().map(|p| (*p, 0))); a.extend(p[1].iter().map(|p| (*p, 1))); a.sort(); let mut left = std::collections::BinaryHeap::new(); let mut add = 0; left.push((0, inf)); if a[0].1 == 0 { add += 1; } else { add -= 1; } for a in a.windows(2) { let diff = a[1].0 - a[0].0; let mut d = diff; let mut l = diff; while d > 0 && left.peek().map_or(false, |p| p.0 + add > 0) { let (a, b) = *left.peek().unwrap(); let a = a + add; let v = b.min(d); sum += a * v; d -= v; l += v; if b == v { left.pop(); } else { left.peek_mut().unwrap().1 -= v; } } left.push((-add, l)); if a[1].1 == 0 { add += 1; } else { add -= 1; } } for v in left.drain() { let pos = v.0 + add; let cnt = v.1; sum += cnt * std::cmp::max(pos, 0); } cnt += p[0].len(); } if cnt == n.min(m) { println!("{}", sum); } else { println!("-1"); } } fn main() { run(); } // ---------- begin input macro ---------- // reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 #[macro_export] 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_export] 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_export] 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") }; } // ---------- end input macro ----------