#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>

class union_find {
public:
    union_find(int n)
        : par_(n, -1)
    {}
    void init(int n) {
        par_.assign(n, -1);
    }

    int root(int x) {
        return par_[x] < 0 ? x : par_[x] = root(par_[x]);
    }

    bool unite(int x, int y) {
        x = root(x); y = root(y);
        if(x == y) {
            return false;
        } else {
            if(par_[x] < par_[y]) {
                par_[x] += par_[y];
                par_[y] = x;
            } else {
                par_[y] += par_[x];
                par_[x] = y;
            }
            return true;
        }
    }

    bool same(int x, int y) {
        return root(x) == root(y);
    }

    int size(int x) {
        return -par_[root(x)];
    }

private:
    std::vector<int> par_;
};

int main()
{
  typedef std::pair<int,std::pair<int,int> > bridge;
  int n,m;
  while (true) {
    std::cin >> n >> m;
    if (n==0 && m==0) {
      break;
    }
    int totalcost = 0;
    std::vector<bridge> bridges(m);
    for (int i = 0; i < m; i++) {
      int a,b,cost;
      std::cin >> a >> b >> cost;
      bridges[i] = bridge(cost,std::make_pair(a,b));
    }
    std::sort(bridges.begin(),bridges.end());
    union_find reachable(n);
    for (int i = 0; i < m; i++) {
      if (!(reachable.same(bridges[i].second.first,bridges[i].second.second))) {
	totalcost += bridges[i].first;
	reachable.unite(bridges[i].second.first,bridges[i].second.second);
      }
    }
    std::cout << totalcost << std::endl;
  }
}