#include <iostream>
#include <cstdio>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
const int SIZE = 105;
int N,M;
int FATHER[SIZE];
int MAP[SIZE][SIZE];
struct Node
{
int from,to,cost;
}G[SIZE];
void ini(void);
int find_father(int);
void unite(int,int);
bool same(int,int);
bool comp(const Node &,const Node &);
int kruskal(void);
int main(void)
{
int from,to,cost;
while(~scanf("%d",&N))
{
if(!N)
break;
scanf("%d",&M);
ini();
for(int i = 0;i < M;i ++)
scanf("%d%d%d",&G[i].from,&G[i].to,&G[i].cost);
sort(G,G + M,comp);
printf("%d\n",kruskal());
}
return 0;
}
void ini(void)
{
fill(&MAP[0][0],&MAP[SIZE - 1][SIZE - 1],-1);
for(int i = 1;i <= N;i ++)
FATHER[i] = i;
}
int find_father(int n)
{
if(n == FATHER[n])
return n;
return FATHER[n] = find_father(FATHER[n]);
}
void unite(int x,int y)
{
x = find_father(x);
y = find_father(y);
if(x == y)
return ;
FATHER[x] = y;
}
bool same(int x,int y)
{
return find_father(x) == find_father(y);
}
int kruskal(void)
{
int ans = 0,count = 0;
for(int i = 0;i < M;i ++)
if(!same(G[i].from,G[i].to))
{
unite(G[i].from,G[i].to);
ans += G[i].cost;
count ++;
if(count == N - 1)
break;
}
return ans;
}
bool comp(const Node & a,const Node & b)
{
return a.cost < b.cost;
}