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

struct Edge {
	int s;
	int t;
	int cost;
	Edge() {}
	Edge(int s, int t, int cost) : s(s), t(t), cost(cost) {}
};
bool operator < (const Edge& e, const Edge& f) { return e.cost < f.cost; }

int root(int* par, int x)
{
	if (x==par[x]) return x;
	else return par[x] = root(par, par[x]);
}

void unite(int* par, int x, int y)
{
	par[root(par, x)] = root(par, y);
}

bool isSame(int* par, int x, int y)
{
	return root(par, x) == root(par, y);
}

int main()
{
	int n, m;
	while (true) {
		std::cin >> n >> m;
		if (n == 0) break;
		std::vector<Edge> edge_list;
		for (int i=0; i<m; i++) {
			int s, t, cost;
			std::cin >> s >> t >> cost;
			edge_list.push_back( Edge(s, t, cost) );
		}
		std::sort(edge_list.begin(), edge_list.end());
		int* par = new int[n];
		for (int i=0; i<n; i++) par[i] = i;
		int res = 0;
		int count = 0;
		for (int i=0; i<edge_list.size(); i++) {
			if (isSame(par, edge_list[i].s, edge_list[i].t)) continue;
			unite(par, edge_list[i].s, edge_list[i].t);
			res += edge_list[i].cost;
			count++;
			if (count == n-1) break;
		}
		std::cout << res << std::endl;
		delete[] par;
	}
	return 0;
}

