import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.io.StdIn.* import scala.util.chaining.* import scala.math.* class UnionFind(val size: Int): private val vec = Array.fill(size){-1} def find(a: Int): Int = if vec(a) < 0 then a else vec(a) = find(vec(a)) vec(a) def same(a: Int, b: Int): Boolean = find(a) == find(b) def unite(a: Int, b: Int): Unit = val i = find(a) val j = find(b) if i != j then if vec(i) < vec(j) then vec(i) += vec(j) vec(j) = i else vec(j) += vec(i) vec(i) = j @main def main = val Array(n, m) = readLine().split(' ').map(_.toInt) val a = readLine().split(' ').map(_.toInt) val b = readLine().split(' ').map(_.toInt) val aSet = a.toSet val allCell = (a ++ b).sorted val uft = UnionFind(n + m + 1) for i <- 0 until n + m if aSet.contains(allCell(i)) do uft.unite(i, n + m) var result = 0 for i <- (1 until n + m).sortBy(i => allCell(i) - allCell(i - 1)) do if !uft.same(i, i - 1) then uft.unite(i, i - 1) result += allCell(i) - allCell(i - 1) println(result)