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

int n,m,sum;
int P[110],a[10010],b[10010],cost[10010];
pair<int,int> bridge[10010];
void init(int N) {
	for(int i=0; i<N; ++i) P[i] = i;
}
int root(int a) {
	if(P[a] == a) return a;
	return (P[a] = root(P[a]));
}

int main() {
	cin >> n >> m;
	while(n!=0 && m!=0) {
		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);
		init(n);
		for(int i=0; i<m; ++i) {
			if(P[b[bridge[i].second]] == b[bridge[i].second]) {
				if(P[a[bridge[i].second]] != b[bridge[i].second]) {
					P[b[bridge[i].second]] = a[bridge[i].second];
					root(b[bridge[i].second]);
					sum += bridge[i].first;
				}
			}
		}
		cout << sum << endl;
		cin >> n >> m;
		sum =0;
	}
}