#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int N, M, A[10010], B[10010], COST[10010], parent[10010];
pair<int, int> bridge[10010];

void init(int N){
  for(int i=0; i<N; ++i) parent[i] = i;
}
int root(int a){
  if(parent[a] == a) return a;
  return (parent[a] = root(parent[a]));
}
bool is_same_set(int a, int b){
  return root(a) == root(b);
}
void unite(int a, int b){
  parent[root(a)] = root(b);
}

int main(){
  while(cin >> N >> M && N > 0){
    init(N);
    for(int i=0; i<M; ++i){
      cin >> A[i] >> B[i] >> COST[i];
      bridge[i].first = COST[i];
      bridge[i].second = i;
    }
    sort(bridge, bridge+M);

    int sum = 0;

    for(int i=0; i<M; ++i){
      int cost = bridge[i].first;
      int a = A[bridge[i].second];
      int b = B[bridge[i].second];
      if(is_same_set(a, b)) continue;
      unite(a, b);
      sum += cost;
    }
    cout << sum << endl;
  }
  
  return 0;
}