#include <algorithm>
#include <cstdio>
#include <vector>

using namespace std;
#define reps(i,f,n) for(int i=f; i<int(n); ++i)
#define rep(i,n) reps(i,0,n)

typedef vector<int> vi;
typedef vector<vi> vvi;

struct Edge {
	int src, dst, cost;
	Edge(int s, int d, int c) : src(s), dst(d), cost(c) {}
	Edge(){}
	bool operator< (const Edge& e)const {
		return cost < e.cost;
	}
};

struct UnionFind{
	vi par, rank;
	UnionFind(int n) : par(n), rank(n, 0) {
		rep(i, n)
			par[i] = i;
	}

	int find(int a){
		return par[a] == a ? a : (par[a] = find(par[a]));
	}

	bool same(int a, int b){
		return find(a) == find(b);
	}

	void unite(int a, int b){
		a = find(a);
		b = find(b);
		if(a == b)
			return;

		if(rank[a] < rank[b])
			par[a] = b;
		else
			par[b] = a;
		rank[a] += rank[a] == rank[b];
	}
};

int main()
{
	int n, m;
	while(scanf("%d%d", &n, &m), n){
		vector<Edge> E(m);
		rep(i, m){
			int a, b, c;
			scanf("%d%d%d", &a, &b, &c);
			E[i] = Edge(a, b, c);
		}
		sort(E.begin(), E.end());

		int cost = 0;
		UnionFind uf(n);
		rep(i, m){
			if(!uf.same(E[i].src, E[i].dst)){
				uf.unite(E[i].src, E[i].dst);
				cost += E[i].cost;
			}
		}
		printf("%d\n", cost);
	}

	return 0;
}