object Main extends App {

  import scala.io.StdIn._

  solve
  def solve: Unit = {
    val Array(n, m) = readLine.trim.split(' ').map(_.toInt)
    if (n == 0) return
    val cities = Array.tabulate(n){_ ⇒ new UnionFindTree}
    var cost = 0
    for ((a, b, c) ← Array.tabulate(m){_ ⇒
      val Array(a, b, cost) = readLine.trim.split(' ').map(_.toInt)
      (a, b, cost)
    }.sortBy(_._3)){
      if (!cities(a).isSameUnion(cities(b))){
        cities(a).merge(cities(b))
        cost += c
      }
    }
    println(cost)
    solve
  }
  class UnionFindTree{
    private var mParent: Option[UnionFindTree] = None
    private var mSize: Int = 1
    private def parent: UnionFindTree = {
      mParent.map{_.parent} match {
        case None ⇒ this
        case c@Some(p) ⇒
          mParent = c
          p
      }
    }
    def isSameUnion(that: UnionFindTree): Boolean = {
      parent == that.parent
    }
    def merge(that: UnionFindTree): Unit = {
      if (!isSameUnion(that)){
        val p = parent
        val tp = that.parent
        if (p.mSize > tp.mSize){
          tp.mParent = Some(p)
          p.mSize += tp.mSize
        }else {
          p.mParent = Some(tp)
          tp.mSize += p.mSize
        }
      }
    }
  }
  implicit class Extension[T](val value :T) extends AnyVal {
    @inline
    def let[A](@inline func: T ⇒ A): A = func(value)
    @inline
    def also(@inline func: T ⇒ Unit): T = {func(value); value}
  }
}
