#include<bits/stdc++.h>
#define for0(i, n) for(int i = 0; i < (n); i++)
#define for1(i, n) for(int i = 1; i <= (n);i++)
#define mp make_pair
#define all(x) x.begin(),x.end()
using namespace std;
int pt[123456], n, m, ans;
vector<pair<int, pair<int, int>>>v;
void setup() {
	ans = 0; v.clear();
	for0 (i, n)pt[i] = i;
	return;
}
int root(int i) {
	if (pt[i] == i)return i;
	else return pt[i] = root(pt[i]);
}
void unite(int a, int b) {
	pt[root(b)] = root(a);
	root(b);
	return;
}
int main() {
	while (cin >> n >> m, n) {
		setup();
		for0(i, m) {
			int a, b, c; cin >> a >> b >> c;
			v.push_back(mp(c, mp(a, b)));
		}
		sort(all(v));
		for0(i, m) {
			int a = v[i].second.first, b = v[i].second.second, c = v[i].first;
			if (root(a) != root(b)) {
				unite(a, b);
				ans += c;
			}
		}
		cout << ans << endl;
	}
}
