use std::{collections::{BTreeSet, HashMap, BinaryHeap}, cmp::Reverse}; struct UnionFind { n: usize, parents: Vec, depths: Vec, chains: Vec, } impl UnionFind { fn new(n: usize) -> Self { UnionFind { n: n, parents: (0..n).collect(), depths: vec![0; n], chains: vec![1; n], } } fn equiv(&mut self, a: usize, b: usize) -> bool { self.find(a) == self.find(b) } fn unite(&mut self, a: usize, b: usize) { if self.equiv(a, b) { return; } let x = self.parents[a]; let y = self.parents[b]; if self.depths[x] > self.depths[y] { self.parents[x] = self.parents[y]; self.chains[y] += self.chains[x]; } else { self.parents[y] = self.parents[x]; self.chains[x] += self.chains[y]; if self.depths[x] == self.depths[y] { self.depths[x] += 1; } } } fn find(&mut self, a: usize) -> usize { if self.parents[a] == a { return a; } let p = self.find(self.parents[a]); self.parents[a] = p; p } fn chain_cnt(&mut self, i: usize) -> usize { let idx = self.find(i); self.chains[idx] } } fn main() { let mut nm = String::new(); std::io::stdin().read_line(&mut nm).ok(); let nm: Vec = nm.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let n = nm[0]; let m = nm[1]; let mut a = String::new(); std::io::stdin().read_line(&mut a).ok(); let a: BTreeSet = a.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let mut b = String::new(); std::io::stdin().read_line(&mut b).ok(); let b: BTreeSet = b.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let mut uf = UnionFind::new(n+m+1); let mut totals = BTreeSet::new(); for &v in a.iter() { totals.insert(v); } for &v in b.iter() { totals.insert(v); } let mapping = (0..n+m).map(|i| (*totals.iter().nth(i).unwrap(), i)).collect::>(); for &v in a.iter() { uf.unite(*mapping.get(&v).unwrap(), n+m); } let mut pque = BinaryHeap::new(); for &v in b.iter() { let idx = *mapping.get(&v).unwrap(); if let Some(&left) = a.range(..v).rev().nth(0) { let nidx = *mapping.get(&left).unwrap(); pque.push((Reverse(v-left), idx, nidx)); } if let Some(&right) = a.range(v+1..).nth(0) { let nidx = *mapping.get(&right).unwrap(); pque.push((Reverse(right-v), idx, nidx)); } if let Some(&left) = b.range(..v).rev().nth(0) { let nidx = *mapping.get(&left).unwrap(); pque.push((Reverse(v-left), idx, nidx)); } if let Some(&right) = b.range(v+1..).nth(0) { let nidx = *mapping.get(&right).unwrap(); pque.push((Reverse(right-v), idx, nidx)); } } let mut result = 0usize; while let Some((Reverse(cost), l, r)) = pque.pop() { if uf.find(l) == uf.find(r) { continue; } uf.unite(l, r); result += cost; } println!("{}", result); }