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 (S.fromAscList (map (S.singleton) [0..n-1])) 0 edge
 where
  makepath _ acc [] = acc
  makepath ts acc (((a,b),d):abd)
   | sa /= sb = makepath (link sa sb ts) (d+acc) abd
   | otherwise = makepath ts acc abd
   where
    sa = S.findMax $ S.filter (S.member a) ts
    sb = S.findMax $ S.filter (S.member b) ts
    link sa sb ts = S.insert (S.union sa sb) $ S.delete sb $ S.delete sa 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 = 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)))