{-# 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 <- BSL.getContents
  print $ query n vs    

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

query :: Int -> BSL.ByteString -> Int
query n bs = runST $ do
  uf <- initMUF n
  VU.foldr
    (\(i,j,d) cont !acc -> do
        merged <- unionUF uf i j
        if merged then cont (acc+d) else cont acc)
    (return $!)
    (edges n bs)
    0

edges :: Int -> BSL.ByteString -> VU.Vector (Int,Int,Int)
edges n !bs = VU.create $ do
  ixys <- VUM.unsafeNew $ n `shiftL` 1
  foldr (\ !i cont !input0 -> do
    let Just (!xi, !input1) = BSL.readInt $ BSL.dropWhile (<'!') input0
        Just (!yi, !input2) = BSL.readInt $ BSL.dropWhile (<'!') input1
    VUM.unsafeWrite ixys    i  (i,xi)
    VUM.unsafeWrite ixys (n+i) (i,yi)
    cont input2)
    (\ !input -> return ())
    [0..n-1] bs
  rad_count <- VPM.unsafeNew 256
  rad_tmp0 <- VUM.unsafeNew $ n `shiftL` 1 - 1
  rad_tmp1 <- VUM.unsafeNew $ n `shiftL` 1 - 1
  rad_tmp2 <- VUM.unsafeNew $ n `shiftL` 1 - 1
  let rad_tmpA = VUM.unsafeTake n $ VUM.zip rad_tmp0 rad_tmp1
      rad_tmpB = VUM.zip3 rad_tmp0 rad_tmp1 rad_tmp2
  radSort_loop 4 (\k -> let !b = k*8 in \(i,x) -> shiftR x b .&. 255)
    (VUM.unsafeTake n ixys) rad_tmpA rad_count
  radSort_loop 4 (\k -> let !b = k*8 in \(i,y) -> shiftR y b .&. 255)
    (VUM.unsafeDrop n ixys) rad_tmpA rad_count
  let (is, xys) = VUM.unzip ixys
  forM_ [0..2*n-2] $ \i -> do
    v_ip1 <- VUM.unsafeRead xys $ i+1
    VUM.unsafeModify xys (v_ip1-) i
  VUM.unsafeWrite xys (n-1) (2^32-1)
  js <- VUM.clone $ VUM.tail is
  let ijds = VUM.zip3 is js xys
  radSort_loop 4 (\k -> let !b = k*8 in \(i,j,d) -> shiftR d b .&. 255)
    ijds rad_tmpB rad_count
  return ijds


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

initMUF :: Int -> ST s (MUFTree s)
{-# INLINE initMUF #-}
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
{-# INLINE unionUF #-}
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 ->    VUM.write vec rootj rooti
      GT ->    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 k) dst src count >> go False (k+1)
                    else radSort_body (rdx k) src dst count >> go True  (k+1)
   | otherwise  = when swap (VGM.unsafeCopy src dst)
{-# INLINE radSort_loop #-}


radSort_body :: (PrimMonad m, VGM.MVector v e)
     => (e -> Int)                   -- radix function
     -> v (PrimState m) e            -- source array
     -> v (PrimState m) e            -- destination array
     -> VPM.MVector (PrimState m) Int -- radix count
     -> m ()
radSort_body rdx src dst count = do
  radSort_countLoop rdx src count
  radSort_accum count
  radSort_moveLoop 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)
         => (e -> Int) -> v (PrimState m) e
         -> v (PrimState m) e -> VPM.MVector (PrimState m) Int -> m ()
radSort_moveLoop 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 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: 14716