Infinity = 1000000

def decreaseKey q, v, w
  q.size.times do |i|
    if q[i][0] == v
      q[i][1] = w
      break
    end
  end
end

def inQueue q, v
  q.size.times do |i|
    return true if q[i][0] == v
  end
  false
end

def prim graph
  n = graph.size
  key = Array.new(n, Infinity)
  key[0] = 0
  q = Array.new
  n.times do |i|
    q << [i, key[i]]
  end

  until q.empty?
    #最少のキー値を持つノードを取り出す
    u = -1
    min = Infinity
    q.size.times do |i|
      if q[i][1] < min
        min = q[i][1]
        u = q[i][0]
      end
    end
    q.size.times do |i|
      if q[i][0] == u
        q.delete_at(i)
        break
      end
    end

    #そのノードから接続しているすべてのノードについて、キー値を更新する
    n.times do |v|
      next if graph[u][v] == Infinity
      if inQueue(q, v)
        w = graph[u][v]
        #キー値を更新したら、キュー格納値のキーを更新
        if w < key[v]
          key[v] = w
          decreaseKey(q, v, w)
        end
      end
    end
  end
  key
end

loop do
  n,m = $stdin.gets.chomp.split(" ").map(&:to_i)
  break if (n|m) == 0
  graph = Array.new(n).map{Array.new(n, Infinity)}
  m.times do |i|
    a,b,cost = $stdin.gets.chomp.split(" ").map(&:to_i)
    graph[a][b] = cost
    graph[b][a] = cost
  end
  p prim(graph).inject(:+)
end