import Data.List
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Data.Maybe

nub' = S.toList . S.fromList

readInt = fst . fromJust . B.readInt

kruskal n edge = makepath (map return [0..n-1]) [] edge
 where
  makepath _ acc [] = acc
  makepath ts acc (((a,b),d):abd)
   | disjoint a b ts = makepath (link a b ts) ((((a,b),d)):acc) abd
   | otherwise = makepath ts acc abd
   where
    disjoint a b = not . any (\t -> elem a t && elem b t)
    link a b ts = let (ab,ts') = partition (\t -> elem a t || elem b t) ts in concat ab : ts'

main = do
 getLine
 xys <- map (map readInt . B.words) . B.lines <$> B.getContents
 let xyis = zip (nub' xys) [0..]
 let n' = length xyis
 let xysx = sortOn (head.fst) xyis
 let xysy = sortOn (last.fst) xyis
 print (built n' xysx xysy)

built n xysx xysy = sum $ map snd (kruskal n edge)
 where
  edge = sortOn snd (edgex ++ edgey)
  edgex = zipWith make xysx (tail xysx)
  edgey = zipWith make xysy (tail xysy)

make ([xi,yi],i) ([xj,yj],j) = ((i,j), min (abs (xj-xi)) (abs (yj-yi)))