#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>

using namespace std;

#define rep(i,n) for(int i=0; i<(n); i++)
#define repc(i,s,e) for(int i=(s); i<(e); i++)
#define pb(n) push_back((n))
#define mp(n,m) make_pair((n),(m))
#define all(r) r.begin(),r.end()
#define fi first
#define se second

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vl;
typedef vector<vl> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;




const int INF = 1000000;
const int mod = 1e9 + 7;



const int MAX_E = 300100;
const int MAX_V = 100100;
 
int par_uft[MAX_V];
int rank_uft[MAX_V];
 
void init_uft(int n) {
	int i;
	for (i = 0; i < n; i++) {
		par_uft[i] = i;
		rank_uft[i] = 0;
	}
}
 
int find_uft(int x) {
	if (par_uft[x] == x) {
		return x;
	}
	else {
		return par_uft[x] = find_uft(par_uft[x]);
	}
}
 
void unite_uft(int x, int y) {
	x = find_uft(x);
	y = find_uft(y);
	if (x == y)return;
 
	if (rank_uft[x] < rank_uft[y]) {
		par_uft[x] = y;
	}
	else {
		par_uft[y] = x;
		if (rank_uft[x] == rank_uft[y]) {
			rank_uft[x]++;
		}
	}
}
 
bool same_uft(int x, int y) {
	return find_uft(x) == find_uft(y);
}
 
 
 
struct edge { 
	int u, v, cost;
	edge(){}
	edge(int u,int v,int cost):u(u),v(v),cost(cost){}
};
 
bool comp(const edge& e1, const edge& e2) {
	return e1.cost < e2.cost;
}
 
edge es[MAX_E];
int V, E;
 
ll kruskal() {
	sort(es, es + E, comp);
	init_uft(V);
	ll res = 0LL;
	for (int i = 0; i < E; i++) {
		edge e = es[i];
		if (!same_uft(e.u, e.v)) {
			unite_uft(e.u, e.v);
			res += e.cost;
		}
	}
	return res;
}



int main(){
	int n,m;
	while(cin>>n>>m && n>0 ) {
		V=n; E=m*2;
		int a,b,c;
		for(int i=0; i<m; i++){
			cin>>a>>b>>c;
			es[i*2] =edge(a,b,c);
			es[i*2+1] = edge(b,a,c);
		}
		cout<<kruskal()<<endl;
	}
}