import Data.Maybe
import Data.List
import qualified Data.Set as H
import qualified Data.IntMap as M
import qualified Data.IntSet as S
import qualified Data.ByteString.Char8 as B

type Index = Int
data Edge = Edge { cost :: Int, src :: Index, dst :: Index } deriving (Show, Eq, Ord)
type Edges = M.IntMap [Edge]
type Node = (Int, Index)

makeEdges :: [Node] -> [Edge]
makeEdges l = [edge | edge@(Edge _ src dst) <- edges', src >= 0 && dst >= 0]
  where
    f (z, (c, i)) (c', j) =
      let cost = c' - c
      in (Edge cost i j : Edge cost j i : z, (c', j))
    (edges', _) = foldl' f ([], (0, -1)) l

upsert :: Edges -> Edge -> Edges
upsert edges edge@(Edge _ src _)
  | M.member src edges = M.update (\curr -> Just (edge : curr)) src edges
  | otherwise = M.insert src [edge] edges

type PQ = H.Set Edge
mst' :: Int -> PQ -> S.IntSet -> Int -> Edges -> Int
mst' total pq visited n edges
  | dst == (-1) = total
  | S.member dst visited = mst' total poped visited n edges
  | otherwise =
      let
          total' = total + cost
          visited' = S.insert dst visited
          nexts = filter (\(Edge _ _ dst') -> S.notMember dst' visited') $ fromJust $ M.lookup dst edges
          pq' = foldl' (flip H.insert) poped nexts
      in mst' total' pq' visited' n edges
  where
    edge@(Edge cost _ dst) = if H.null pq
                             then Edge (-1) (-1) (-1)
                             else H.elemAt 0 pq
    poped = H.deleteAt 0 pq


mst :: Int -> Edges -> Int
mst n edges = mst' 0 pq visited n edges
  where
    edge = fromJust $ M.lookup 0 edges
    pq = H.fromList edge
    visited = S.fromList [0]

solve :: [(Int, Int)] -> Int
solve l = mst n edges
  where
    n = length l
    xs = makeEdges $ sort $ zip (map fst l) [0..]
    ys = makeEdges $ sort $ zip (map snd l) [0..]
    dummy = Edge (-1) (-1) (-1)
    edges = foldl' upsert (M.fromList [(-1,[dummy])]) (xs ++ ys)

toTuple :: [Int] -> (Int, Int)
toTuple [x,y] = (x,y)

readInt = fst . fromJust . B.readInt
main = B.getContents >>= print . solve . map (toTuple . map readInt . B.words) . tail . B.lines
