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

struct Edge {
  int from, to, cost;
  Edge() : from(0), to(0), cost(0) { }
  Edge(int from, int to, int cost) : from(from), to(to), cost(cost) { }
};

struct UnionFind {
  vector<int> data;

  UnionFind(int n) : data(n, -1) { }

  bool same(int i, int j) {
    return root(i) == root(j);
  }

  int root(int i) {
    return data[i] < 0 ? i : data[i] = root(data[i]);
  }

  void join(int i, int j) {
    data[root(i)] += data[root(j)];
    data[root(j)] = root(i);
  }
};

int main() {
  for(int n, m; cin >> n >> m && n; ) {
    vector<Edge> edges(m);

    for(int i = 0; i < m; i++) {
      cin >> edges[i].from >> edges[i].to >> edges[i].cost;
    }

    sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {
      return a.cost < b.cost;
    });

    int cost = 0;
    UnionFind uf(n);

    for(auto it = edges.begin(); it != edges.end(); it++) {
      if(!uf.same(it->from, it->to)) {
        uf.join(it->from, it->to);
        cost += it->cost;
      }
    }

    cout << cost << endl;
  }
}