#include <stdio.h>
#include <vector>
#include <algorithm>

struct union_find {
	std::vector<int> data;

public:
	union_find(int n) : data(n, -1) {}
	bool unite(int x, int y) {
		x = find(x); y = find(y);
		if(x == y) return false;
		if(data[x] > data[y]) std::swap(x, y);
		data[x] += data[y];
		data[y] = x;
		return true;
	}
	int find(int k) {
		if(data[k] < 0) return k;
		return data[k] = find(data[k]);
	}
};

int main() {
	using P = std::pair<int, std::pair<int, int>>;

	int n, m;
	while(scanf("%d%d", &n, &m), n) {
		int ans = 0;
		std::vector<P> vec;
		for(int i = 0; i < m; i++) {
			int a, b, c; scanf("%d%d%d", &a, &b, &c);

			vec.push_back({c, {a, b}});
		}
		sort(begin(vec), end(vec));
		
		union_find uf(n);
		for(auto v: vec) {
			if(uf.unite(v.second.first, v.second.second)) ans += v.first;
		}
		printf("%d\n", ans);
	}
	return 0;
}

