#include<vector>
#include<iostream>
#include<algorithm>

#define	mp(a,b)		make_pair(a,b)
#define	mt(a,b,c)	mp(mp(a,b),c)
#define	_1st	first.first
#define	_2nd	first.second
#define	_3rd	second

using namespace std;

typedef	pair<int,int> pii;
typedef pair<pii,int> tiii;

vector<int> city;

int UF_Root(int i)
{
	if (city[i]==-1)	return i;
	return city[i]=UF_Root(city[i]);
}

bool UF_Find(int i,int j)
{
	return UF_Root(i)==UF_Root(j);
}

void UF_Union(int i,int j)
{
	i=UF_Root(i);
	j=UF_Root(j);
	if(i!=j)	city[j]=i;
}

int main()
{
	for(int n,m;cin>>n>>m,n;){
		city=vector<int>(n,-1);

		vector<tiii> data(m);
		while(m--){
			int a,b,c;	cin>>a>>b>>c;
			data[m]=mt(c,a,b);
		}
		sort(data.begin(),data.end());

		int totalcost=0;
		for(int i=0;i<data.size();i++){
			if(!UF_Find(data[i]._2nd,data[i]._3rd)){
				UF_Union(data[i]._2nd,data[i]._3rd);
				totalcost+=data[i]._1st;
			}
		}
		cout<<totalcost<<endl;
	}

	return 0;
}