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

class UnionFind {
private:
  int *par, *rank;

public:
  UnionFind() {}
  UnionFind(int n) {
    par = new int[n];
    rank = new int[n];
    for(int i = 0; i < n; ++i) {
      par[i] = i;
      rank[i] = 0;
    }
  }

  int find(int x) {
    if(par[x] == 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[x] = y;
    } else {
      par[y] = x;
      if(rank[x] == rank[y]) {
        ++rank[x];
      }
    }
  }
};


int main() {
  int n, m;
  while(cin >> n >> m && (n|m)) {
    pair<int,pair<int,int> > es[m];
    for(int i = 0; i < m; ++i) {
      cin >> es[i].second.first
          >> es[i].second.second
          >> es[i].first;
    }
    sort(es, es+m);
    UnionFind uf(n);
    int res = 0;
    for(int i = 0; i < m; ++i) {
      int a = es[i].second.first;
      int b = es[i].second.second;
      if(!uf.same(a,b)) {
        res += es[i].first;
        uf.unite(a,b);
      }
    }
    cout << res << endl;
  }
  return 0;
}