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

struct UF {
  int *p;
  UF(int N):p(new int[N]) {fill(p,p+N,-1);}
  ~UF(){delete[] p;}
  int rt(int x){return p[x]<0?x:(p[x]=rt(p[x])); }
  bool cat(int x,int y) {
    if((x=rt(x))==(y=rt(y)))return false;
    if(p[x]<p[y])swap(x,y);
    p[y]+=p[x];
    p[x]=y;
    return true;
  }
};

int main() {
  for(int tci = 0; ; tci++) {
    int n,m; scanf("%d%d", &n, &m);
    if(n==0) break;
    pair<int,pair<int,int> > *edges = new pair<int,pair<int,int> >[m];
    for(int i = 0; i < m; i++) {
      scanf("%d%d%d", &edges[i].second.first, &edges[i].second.second, &edges[i].first);
    }
    sort(edges,edges+m);
    long long costsum = 0;
    UF uf(n);
    for(int i = 0; i < m; i++) {
      if(uf.cat(edges[i].second.first,edges[i].second.second)) {
        costsum += edges[i].first;
      }
    }
    printf("%lld\n", costsum);
    delete[] edges;
  }
  return 0;
}