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 allCell = Array.fill(n + m){0} val isRed = Array.fill(n + m){false} { var ai = 0 var bi = 0 for i <- 0 until n + m do if bi == m || (ai != n && a(ai) < b(bi)) then allCell(i) = a(ai) isRed(i) = true ai += 1 else allCell(i) = b(bi) bi += 1 } val uft = UnionFind(n + m + 1) for i <- 0 until n + m if isRed(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 result += allCell(i) - allCell(i - 1) uft.unite(i, i - 1) println(result)