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

class union_find {
private:
	vector<int> uf;

public:
	union_find(int n):uf(n, -1){}

	inline int find(int x) {
		return uf[x] < 0 ? x : uf[x] = find(uf[x]);
	}

	inline bool unite(int x, int y) {
		x = find(x);
		y = find(y);
		if(x == y)
			return false;

		if(uf[x] > uf[y])
			swap(x, y);

		else if(uf[x] == uf[y])
			--uf[x];

		uf[y] = x;

		return true;
	}
};

typedef int weight;
struct edge {
	int u, v;
	weight cost;
	edge(int u, int v, weight c):u(u), v(v), cost(c){}

	bool operator< (const edge& o) const {
		return cost < o.cost;
	}
};

int n, m;
vector<edge> es;

weight kruskal() {
	sort(es.begin(), es.end());
	union_find uf(n);

	weight res = 0;
	for(int i = 0; i < es.size(); ++i)
		if(uf.unite(es[i].u, es[i].v))
			res += es[i].cost;

	return res;
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	while(cin >> n >> m && n) {
		es.clear();
		for(int i = 0; i < m; ++i) {
			int u, v, cost;
			cin >> u >> v >> cost;
			es.emplace_back(u, v, cost);
		}

		cout << kruskal() << endl;
	}


	return EXIT_SUCCESS;
}