#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> P;

struct UnionFind{
    vector<int> par;
    UnionFind(int N) : par(N){
        for(int i = 0; i < N; i++){
            par[i] = -1;
        }
    }
    int root(int x){
        if(par[x] < 0) return x;
        else return par[x] = root(par[x]);
    }
    void unite(int x, int y){
        int rx = root(x);
        int ry = root(y);
        if(rx == ry) return;
        else{
            if(par[rx] > par[ry]) swap(rx, ry);
            par[rx] += par[ry];
            par[ry] = rx;
       }
    }
    bool same(int x, int y){
        return root(x) == root(y);
    }
    void check(){
        for(auto x : par){
            cout << x << " ";
        }
        cout << endl;
    }
};

int n, m;
vector<pair<int, P>> G; // {cost, {vertex_1, vertex_2}}



int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    while(cin >> n >> m){
        if(n == 0 and m == 0) break;
    
        G.resize(m);

        for(int i = 0; i < m; i++){
            int a, b, cost;
            cin >> a >> b >> cost;
            G[i] = {cost, {a, b}};
        }

        sort(G.begin(), G.end());

        UnionFind uf(n);

        int ans = 0;
        for(int i = 0; i < m; i++){
            pair<int, P> A = G[i];
            int c = A.first;
            int u = A.second.first;
            int v = A.second.second;
            if(uf.root(u) == uf.root(v)) continue;

            ans += c;
            uf.unite(u, v);
        }

        cout << ans << endl;

    }

    return 0;
}
