#include <algorithm>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

#define FOR(i,k,n) for (int (i)=(k); (i)<(n); ++(i))
#define rep(i,n) FOR(i,0,n)
#define pb push_back
#define eb emplace_back
#define all(v) begin(v), end(v)
#define debug(x) cerr<< #x <<": "<<x<<endl
#define debug2(x,y) cerr<< #x <<": "<< x <<", "<< #y <<": "<< y <<endl

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> i_i;
typedef pair<i_i, int> p_i;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef vector<ll> vll;
typedef vector<vector<ll> > vvll;
typedef vector<char> vc;
typedef vector<vector<char> > vvc;
typedef vector<double> vd;
typedef vector<vector<double> > vvd;
template<class T> using vv=vector<vector< T > >;
typedef deque<int> di;
typedef deque<deque<int> > ddi;

// cout vector
template<typename T> ostream& operator<<(ostream& s, const vector<T>& v) {
    int len = v.size();
    for (int i = 0; i < len; ++i) {
        s << v[i]; if (i < len - 1) s << "\t";
    }
    return s;
}

// cout 2-dimentional vector
template<typename T> ostream& operator<<(ostream& s, const vector< vector<T> >& vv) {
    int len = vv.size();
    for (int i = 0; i < len; ++i) {
        s << vv[i] << endl;
    }
    return s;
}

struct union_find {
    int n;
    vi d;
    union_find() {}
    union_find(int n_): n(n_), d(n, -1) {}
    int root(int v) {
        if (d[v] < 0) {
            return v;
        }
        return d[v] = root(d[v]);
    }
    int size(int v) {
        return -d[root(v)];
    }
    bool unite(int x, int y) {
        x = root(x);
        y = root(y);
        if (x == y) {
            return false;
        }
        if (size(x) < size(y)) {
            swap(x, y);
        }
        d[x] += d[y];
        d[y] = x;
        return true;
    }
};

int main() {
    while (true) {
        int n, m;
        cin >> n >> m;
        if ( n == 0 ) { break; }
        vvi edges(m);
        rep (i, m) {
            int a, b, cost;
            cin >> a >> b >> cost;
            edges[i] = {cost, a, b};
        }
        sort(all(edges));

        int ans = 0;
        union_find uf(n);
        rep (i, m) {
            if ( uf.unite(edges[i][1], edges[i][2]) ) {
                ans += edges[i][0];
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}