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

using namespace std;

struct UnionFind {
  vector<int> data;
  UnionFind(int size) : data(size, -1) { }

  bool merge(int x, int y){
    int root_x = find(x);
    int root_y = find(y);
    if(root_x != root_y){
      if(data[root_y] < data[root_x]){
	swap(root_x, root_y);
      }
      data[root_x] += data[root_y];
      data[root_y] = root_x;
    }
    
    return root_x != root_y;
  }
  
  int find(int x){
    if(data[x] < 0){
      return x;
    }else{
      return find(data[x]);
    }
  }

  bool is_same(int x, int y){
    return find(x) == find(y);
  }
  
  int size(int x){
    return -find(x);
  }
};

typedef pair<long long int, pair<long long int, long long int> > Edge;

inline Edge make_edge(int a, int b, int c){
  return make_pair(c, make_pair(a, b));
}

int main(int argc, char* argv[]){

  while( true ) {

    long long int n, m;
    cin >> n >> m;
    if ( n == 0 ) break;

    priority_queue< Edge, vector< Edge >, greater< Edge > > q;

    for ( long long int i = 0; i < m; i++ ) {

      long long int a, b, c;
      cin >> a >> b >> c;
      q.push(make_edge(a, b, c));
    }

    
    UnionFind uf(n);
    long long int costs = 0;
    while(!q.empty()){
      Edge edge = q.top(); q.pop();
      const int from = edge.second.first;
      const int to = edge.second.second;

      if(!uf.is_same(from, to)){
	uf.merge(from, to);
	//	cout << edge.first << endl;
	costs += edge.first;
      }
    }
 
    cout << costs << endl;
  }

  return 0;
  
}