#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <time.h>
 
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define FFOR(i,a,b) for(int i=(a);i<=(b);i++)
#define REP(i,b) FOR(i,0,b)
#define RREP(i,b) FFOR(i,1,b)
#define PB push_back
#define F first
#define S second
#define BE(c) c.begin(),c.end()
using namespace std;
typedef long long LL;
typedef int ut;
typedef long double ld;
typedef pair<ut,ut> pr;
typedef vector<pr> Vpr;
typedef vector<ut> VI;
typedef pair<ut,pr> ppr;
typedef priority_queue<pr,Vpr, greater<pr> > PQ;
const int SIZE=1e+5 + 1;
const ut INF=1<<30;
const ld eps=1e-6;
const LL mod=1e+9 + 7;

int N, M;
vector<ppr> G;

const int MAX_N = 1000;

int par[MAX_N + 1], r[MAX_N + 1];

void init(int n){
	for(int i = 0; i < n; ++i){
		par[i] = i;
		r[i] = 0;
	}	
}

int find(int x){
	if(par[x] == x)
		return x;
	else
		return par[x] = find(par[x]);
}

void unite(int x, int y){
	x = find(x);
	y = find(y);
	if(x == y)
		return;
		
	if(r[x] < r[y]){
		par[x] = y;
	}
	else{
		par[y] = x;
		if(r[x] == r[y])
			r[x]++;
	}
}

bool same(int x, int y){
	return find(x) == find(y);
}

int main() {
	while(cin >> N >> M && N){
		G.clear();
		REP(i,M){
			int a, b, c;
			scanf("%d%d%d", &a, &b, &c);
			G.PB(ppr(c, pr(a, b)));
		}
		init(N+1);
		sort(BE(G));
		int ans = 0;
		REP(i,G.size()){
			ppr e = G[i];
			if(!same(e.S.F, e.S.S)){
				unite(e.S.F, e.S.S);
				ans += e.F;
			}
		}
		cout << ans << endl;
	}
  return 0;
}