#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> uni;
int find(int at){
    if(at==uni[at]) return at;
    else return uni[at]=find(uni[at]);
}
void unite(int a,int b){
    uni[find(a)]=find(b);
}

int main(){
    for(;;){
        int n,m;
        scanf("%d%d",&n,&m);
        if(n==0&&m==0) break;
        vector<pair<int,pair<int,int> > > costs;
        uni=vector<int>(n);
        for(int i=0;i<n;i++){
            uni[i]=i;
        }
        for(int i=0;i<m;i++){
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            costs.push_back(make_pair(c,make_pair(a,b)));
        }
        sort(costs.begin(),costs.end());
        int ret=0;
        for(int i=0;i<costs.size();i++){
            int a=costs[i].second.first,b=costs[i].second.second,co=costs[i].first;
            if(find(a)!=find(b)){
                ret+=co;
                unite(a,b);
            }
        }
        printf("%d\n",ret);
    }
}