{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleContexts #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IMS
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import Control.Monad
import Control.Monad.ST
-- import Control.Monad.ST.Safe
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import System.IO
import Data.Function
import Control.Monad.Primitive
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic.Mutable as VGM
import Data.STRef
import Data.IORef


main :: IO ()
main = do
  n <- read <$> getLine
  vs <- VU.unfoldrN n (runStateT $ (,) <$> rInt <*> rInt) <$> BSL.getContents
  print $ query vs    

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

  
query :: VU.Vector (Int,Int) -> Int
query vs = runST $ do
  uf <- initMUF $ VU.length vs
  acc <- newSTRef (0::Int)
  VU.forM_ (edges vs) $ \(i,j,d) -> do
    merged <- unionUF uf i j
    when merged $ do
      !prev <- readSTRef acc
      writeSTRef acc $! prev+d
  readSTRef acc

edges :: VU.Vector (Int,Int) -> VU.Vector (Int,Int,Int)
edges vs = VU.create $ do
  vec <- VU.unsafeThaw $ xedges VU.++ yedges
  radSortBy 4 256 (\k -> let b = k*8 in \(i,j,d) -> shiftR d b .&. 255) vec
  return vec
  where
    xedges = VU.zipWith (\(i0,x0) (i1,x1) -> (i0,i1,abs (x0 - x1)))
              ixs (VU.tail ixs)
    yedges = VU.zipWith (\(i0,y0) (i1,y1) -> (i0,i1,abs (y0 - y1)))
              iys (VU.tail iys)
    ixs = VU.create $ do
      ixs <- VU.unsafeThaw $ VU.indexed xs
      radSortBy 4 256 (\k -> let b = k*8 in \(i,x) -> shiftR x b .&. 255) ixs
      return ixs
    iys = VU.create $ do
      iys <- VU.unsafeThaw $ VU.indexed ys
      radSortBy 4 256 (\k -> let b = k*8 in \(i,x) -> shiftR x b .&. 255) iys
      return iys
    (xs,ys) = VU.unzip vs


type MUFTree s = VUM.MVector s Int
type UFTree = VU.Vector Int

initMUF :: Int -> ST s (MUFTree s)
initMUF len = VUM.replicate len minBound

findUF :: MUFTree s -> Int -> ST s Int
{-# INLINE findUF #-}
findUF vec j = do
  vj <- VUM.read vec j
  if vj < 0 then
    return j
  else do
    root <- findUF vec vj
    VUM.write vec j root
    return root
 
unionUF :: MUFTree s -> Int -> Int -> ST s Bool
unionUF vec i j = do
  rooti <- findUF vec i
  rootj <- findUF vec j
  if rooti == rootj then
    return False
  else do
    ranki <- VUM.read vec rooti
    rankj <- VUM.read vec rootj
    case compare ranki rankj of
      LT -> do VUM.write vec rootj rooti
      GT -> do VUM.write vec rooti rootj
      EQ -> do VUM.write vec rootj rooti
               VUM.write vec rooti (ranki+1)
    return True


{-
The following code for radix sort of MVector is a modified version
of what I took from the package vector-algorithm (in hackage),
whose licensing document is follows:


Copyright (c) 2015 Dan Doel
Copyright (c) 2015 Tim Baumann

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. Neither the name of the author nor the names of his contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

------------------------------------------------------------------------------

The code in Data.Array.Vector.Algorithms.Mutable.Optimal is adapted from a C
algorithm for the same purpose. The folowing is the copyright notice for said
C code:

Copyright (c) 2004 Paul Hsieh
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

    Neither the name of sorttest nor the names of its contributors may be
    used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

-}

radSortBy :: (PrimMonad m, VGM.MVector v e)
       => Int               -- ^ the number of passes
       -> Int               -- ^ the size of auxiliary arrays
       -> (Int -> e -> Int) -- ^ the radix function
       -> v (PrimState m) e -- ^ the array to be sorted
       -> m ()
radSortBy passes size rdx arr = do
  tmp    <- VGM.new (VGM.length arr)
  count  <- VPM.new size
  radSort_loop passes rdx arr tmp count
{-# INLINE radSortBy #-}



radSort_loop :: (PrimMonad m, VGM.MVector v e)
          => Int                          -- passes
          -> (Int -> e -> Int)            -- radix function
          -> v (PrimState m) e            -- array to sort
          -> v (PrimState m) e            -- temporary array
          -> VPM.MVector (PrimState m) Int -- radix count array
          -> m ()
radSort_loop passes rdx src dst count = go False 0
 where
 len = VGM.length src
 go swap k
   | k < passes = if swap
                    then radSort_body rdx dst src count k >> go (not swap) (k+1)
                    else radSort_body rdx src dst count k >> go (not swap) (k+1)
   | otherwise  = when swap (VGM.unsafeCopy src dst)
{-# INLINE radSort_loop #-}


radSort_body :: (PrimMonad m, VGM.MVector v e)
     => (Int -> e -> Int)            -- radix function
     -> v (PrimState m) e            -- source array
     -> v (PrimState m) e            -- destination array
     -> VPM.MVector (PrimState m) Int -- radix count
     -> Int                          -- current pass
     -> m ()
radSort_body rdx src dst count k = do
  radSort_countLoop (rdx k) src count
  radSort_accum count
  radSort_moveLoop k rdx src dst count
{-# INLINE radSort_body #-}

radSort_accum :: (PrimMonad m)
           => VPM.MVector (PrimState m) Int -> m ()
radSort_accum count = go 0 0
 where
 len = VPM.length count
 go i acc
   | i < len   = do ci <- VPM.unsafeRead count i
                    VPM.unsafeWrite count i acc
                    go (i+1) (acc + ci)
   | otherwise = return ()
{-# INLINE radSort_accum #-}

radSort_moveLoop :: (PrimMonad m, VGM.MVector v e)
         => Int -> (Int -> e -> Int) -> v (PrimState m) e
         -> v (PrimState m) e -> VPM.MVector (PrimState m) Int -> m ()
radSort_moveLoop k rdx src dst prefix = go 0
 where
 len = VGM.length src
 go i
   | i < len    = do srci <- VGM.unsafeRead src i
                     pf   <- vec_inc prefix (rdx k srci)
                     VGM.unsafeWrite dst pf srci
                     go (i+1)
   | otherwise  = return ()
{-# INLINE radSort_moveLoop #-}


radSort_countLoop :: (PrimMonad m, VGM.MVector v e)
          => (e -> Int)
          -> v (PrimState m) e -> VPM.MVector (PrimState m) Int -> m ()
radSort_countLoop rdx src count = VPM.set count 0 >> go 0
 where
 len = VGM.length src
 go i
   | i < len    = VGM.unsafeRead src i >>= vec_inc count . rdx >> go (i+1)
   | otherwise  = return ()
{-# INLINE radSort_countLoop #-}


vec_inc :: (PrimMonad m, VGM.MVector v Int) => v (PrimState m) Int -> Int -> m Int
vec_inc arr i = VGM.unsafeRead arr i
  >>= \e -> VGM.unsafeWrite arr i (e+1) >> return e
{-# INLINE vec_inc #-}


{- radix-sort ends here  -}


Measured memory_bytes: 19580