#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;

int N, M , A[10010], B[10010], COST[10010];
int P[10010];
int Rank[10010];
pair<int, int> bridge[10010];

void init(int N){
	for(int i = 0; i < N; ++i){
		P[i] = i;
		Rank[i] = 0;
	}
}

int root(int a){
	if(P[a] == a) return a;
	return (P[a] = root(P[a]));
}

bool IsSameSet(int a, int b){
	return root(a) == root(b);
}

void unite(int a, int b){
	P[root(a)] = root(b);
}

void link(int a, int b){
	if(Rank[a] > Rank[b]){
		P[b] = a;
	} else {
		P[a] = b;
		if(Rank[a] == Rank[b]) Rank[a]++;
	}
}

int main(){
	int a,b;
	while(cin >> N >> M, N > 0 && M > 0){
		init(N);
		for(int i=0; i<M; i++){
			cin >> A[i] >> B[i] >> COST[i];
			bridge[i].first = COST[i];
			bridge[i].second = i;
		}		
		sort(bridge, bridge + M);
		int sum = 0;
		for (int i = 0; i < M; ++i){
			int a = A[bridge[i].second];
			int b = B[bridge[i].second];
			if(IsSameSet(a,b)) continue;
			unite(a,b);
			sum += bridge[i].first;
		}
		cout << sum << endl;

	}

}