let init n = Array.make n (-1)

let rec find x p =
  if p.(x) < 0 then x else begin
    let x' = find p.(x) p in p.(x) <- x'; x'
  end

let unite x y p =
  let x', y' = find x p, find y p in
  if x' = y' then () else
  if p.(x') < p.(y') then (p.(y') <- x)
  else begin
    if p.(x') = p.(y') then p.(y') <- p.(y') - 1;
    p.(x') <- y'
  end

let same x y p = find x p = find y p

let () =
  Scanf.scanf "%d" @@ fun n ->
  let cs = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in
  let xs, ys =
    Array.mapi (fun i (x,_) -> (x,i)) cs, Array.mapi (fun i (_,y) -> (y,i)) cs in

  Array.sort compare xs; Array.sort compare ys;

  let edges = Array.concat [
    Array.init (n-1) (fun i ->
      let (x0,i), (x1,j) = xs.(i+1), xs.(i) in (x0-x1, i, j));
    Array.init (n-1) (fun i ->
      let (y0,i), (y1,j) = ys.(i+1), ys.(i) in (y0-y1, i, j));
  ] in
  Array.sort compare edges;

  let uf = Array.make n (-1) in
  Array.fold_left (fun sw (d, i, j) ->
    if same i j uf then sw
    else (unite i j uf; sw+d)) 0 edges
  |> Printf.printf "%d\n"
