#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef complex<double> P;
typedef pair<int,int> pii;
#define REP(i,n) for(ll i=0;i<n;++i)
#define REPR(i,n) for(ll i=1;i<n;++i)
#define FOR(i,a,b) for(ll i=a;i<b;++i)

#define DEBUG(x) cout<<#x<<": "<<x<<endl
#define DEBUG_VEC(v) cout<<#v<<":";REP(i,v.size())cout<<" "<<v[i];cout<<endl
#define ALL(a) (a).begin(),(a).end()

#define MOD (ll)(1e9+7)
#define ADD(a,b) a=((a)+(b))%MOD
#define FIX(a) ((a)%MOD+MOD)%MOD

// http://www.prefield.com/algorithm/container/union_find.html
struct UnionFind {
  vector<int> data;
  UnionFind(int size) : data(size, -1) { }
  bool unionSet(int x, int y) {
    x = root(x); y = root(y);
    if (x != y) {
      if (data[y] < data[x]) swap(x, y);
      data[x] += data[y]; data[y] = x;
    }
    return x != y;
  }
  bool findSet(int x, int y) {
    return root(x) == root(y);
  }
  int root(int x) {
    return data[x] < 0 ? x : data[x] = root(data[x]);
  }
  int size(int x) {
    return -data[root(x)];
  }
};

int main(){
  while(true){
    int n,m;
    cin>>n>>m;
    if(n==0 && m==0)break;
    int res = 0;
    vector< pair<int,pii> > edges(m);
    REP(i,m){
      int a,b,c;
      cin>>a>>b>>c;
      edges[i] = make_pair(c,make_pair(a,b));
    }
    sort(ALL(edges));
    UnionFind uf(n);
    REP(i,m){
      int a,b,c;
      c = edges[i].first;
      a = edges[i].second.first;
      b = edges[i].second.second;
      if(!uf.findSet(a,b)){
        uf.unionSet(a,b);
        res += c;
      }
    }
    cout << res << endl;
  }
  return 0;
}