#include <bits/stdc++.h>
#define rep(i, a, n) for(int i = a; i < n; i++)
#define repb(i, a, b) for(int i = a; i >= b; i--)
#define all(a) a.begin(), a.end()
#define int long long
using namespace std;

struct data{
    int a, b, cost;
};

bool cmp(data d1, data d2){
    return d1.cost < d2.cost;
}

struct UF{
    vector<int> par;
    vector<int> sz;
    void init(int n){
        par.resize(n);
        sz.resize(n, 1);
        rep(i, 0, n) par[i] = i;
    }
    int find(int x){
        if(x == par[x]) return x;
        return par[x] = find(par[x]);
    }
    void unite(int x, int y){
        x = find(x); y = find(y);
        if(x == y) return;
        if(sz[x] < sz[y]) swap(x, y);
        sz[x] += sz[y];
        par[y] = x;
    }
    bool same(int x, int y){
        return find(x) == find(y);
    }
};

signed main(){
    int n, m;
    while(1){
        cin >> n >> m;
        if(n + m == 0) break;
        vector<data> d(m);
        rep(i, 0, m){
            cin >> d[i].a >> d[i].b >> d[i].cost;
        }
        sort(all(d), cmp);
        UF uf;
        uf.init(n);
        int ans = 0;
        rep(i, 0, m){
            int u = d[i].a, v = d[i].b;
            if(!uf.same(u, v)){
                uf.unite(u, v);
                ans += d[i].cost;
            }
        }
        cout << ans << endl;
    }  
}