import Control.Monad

main :: IO ()
main = do
  nm <- getLine
  if nm == "0 0"
    then return ()
    else do
      let [n,m] = map (read :: String -> Int) (words nm)
      ls <- replicateM m getLine
      let ls' = lastSort (map (map (read :: String -> Int)) (map words ls))
          points = [(x,x) | x <- [0..(n-1)]]
          ans = solve points ls'
      putStrLn $ show ans
      main

lastSort :: [[Int]] -> [[Int]]
lastSort [] = []
lastSort (x:xs) = (lastSort lower) ++ [x] ++ (lastSort higher)
  where lower = filter (\y -> (last y) <= (last x)) xs
        higher = filter (\y -> (last y) > (last x)) xs

solve :: [(Int,Int)] -> [[Int]] -> Int
solve points ls' = foldl f 0 (loop points ls' [])
  where f :: Int -> [Int] -> Int
        f acc ls = acc + (last ls)

loop :: [(Int,Int)] -> [[Int]] -> [[Int]] -> [[Int]]
--loop points bridges used
loop _ [] used = used
loop points ([p1,p2,cost]:bs) used
  | isConect p1 p2 points = loop points bs used
  | otherwise = loop (update points [p1,p2,cost]) bs ([p1,p2,cost]:used)
  where
    getBelong :: Int -> [(Int,Int)] -> Int
    getBelong i (p:ps)
      | i == (fst p) = (snd p)
      | otherwise = getBelong i ps
      
    isConect :: Int -> Int -> [(Int,Int)] -> Bool
    isConect p1 p2 points = ((getBelong p1 points) == (getBelong p2 points))
    
    update :: [(Int,Int)] -> [Int] -> [(Int,Int)]
    update [] _ = []
    update ((n,b):ps) [i1,i2,cost]
      | b == belong2 = (n,belong1):(update ps [i1,i2,cost])
      | otherwise = (n,b):(update ps [i1,i2,cost])
      where belong1 = getBelong i1 points
            belong2 = getBelong i2 points