#include <iostream>
#include <cstdlib>
using namespace std;

struct Bridge
{
  int a, b, cost;
};

int n, m, ans, parent[10001];
Bridge bridge[10001];

int bridge_comp(const void *a, const void *b)
{
  return ((Bridge *)a)->cost - ((Bridge *)b)->cost;
}

int root(int a)
{
  if (parent[a] == a) return a;
  else return (parent[a] = root(parent[a]));
}

int main()
{
  while((cin >> n >> m), n && m)
  {
    for (int i = 0; i < n; i++)
      parent[i] = i;
    for (int i = 0; i < m; i++)
      cin >> bridge[i].a >> bridge[i].b >> bridge[i].cost;
    qsort(bridge, m, sizeof(Bridge), bridge_comp);
    ans = 0;
    for (int i = 0; i < m; i++)
    {
      if ((n = root(bridge[i].a)) != root(bridge[i].b))
      {
	parent[root(bridge[i].b)] = n;
	ans += bridge[i].cost;
      }
    }
    cout << ans << endl;
  }
  return 0;
}