use std::collections::{BTreeSet, HashMap}; 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: Vec = 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: Vec = b.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let mut pos = a.iter().copied().collect::>(); for &v in b.iter() { pos.insert(v); } let mapping = pos.iter().enumerate().map(|(i, &v)| (v, i)).collect::>(); let revmap = pos.iter().copied().collect::>(); let a = a.into_iter().map(|v| *mapping.get(&v).unwrap()).collect::>(); let b = b.into_iter().map(|v| *mapping.get(&v).unwrap()).collect::>(); let mut uf = UnionFind::new(pos.len()); for i in 0..n-1 { uf.unite(a[i], a[i+1]); } let mut lines = (0..pos.len()-1).map(|i| (i, revmap[i+1]-revmap[i])).collect::>(); lines.sort_by_key(|&(_, v)| v); let mut result = 0usize; for &(i, cost) in lines.iter() { if uf.find(i) == uf.find(i+1) { continue; } uf.unite(i, i+1); result += cost; } println!("{}", result); }