#include <bits/stdc++.h>

using namespace std;

#define fst(t) std::get<0>(t)
#define snd(t) std::get<1>(t)
#define thd(t) std::get<2>(t)

using ll = long long;
using P = std::tuple<int,int>;
using Q = std::tuple<int,int,int>;

const int dx[8] = {-1, 1, 0, 0, -1, -1, 1, 1}, dy[8] = {0, 0, -1, 1, -1, 1, -1, 1};

template <int n>
struct UnionFind{
    UnionFind(){
        for(int i=0;i<n;i++){
            par[i] = i;
            rank[i] = 0;
        }
    }
    int find(int x){
        if(x == par[x])return x;
        return par[x] = find(par[x]);
    }
    bool same(int x, int y){
        return find(x) == find(y);
    }
    void unite(int x, int y){
        x = find(x);
        y = find(y);
        if(x == y){return;}
        
        if(rank[x] > rank[y]){
            par[y] = x;
        }else{
            par[x] = y;
            if(rank[x] == rank[y]){rank[y]++;}
        }
    }
    int rank[n], par[n];
};

vector<Q> edges;
UnionFind<1000> uf;

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

    int N, M;
    while(true){
        std::cin >> N >> M;

        if(N == 0 && M == 0){return 0;}

        edges.clear();
        uf = UnionFind<1000>();
    
        int sum = 0;
    
        for(int i=0;i<M;++i){
            int u, v, cost;
            std::cin >> u >> v >> cost;

            edges.emplace_back(cost, u, v);
        }
    
        sort(edges.begin(), edges.end());

        for(Q &q : edges){
            int u, v, cost;
            tie(cost, u, v) = q;

            if(uf.same(u, v)){
                continue;
            }

            uf.unite(u, v);
            sum += cost;
        }

        std::cout << sum << std::endl;
    }
}