#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cmath>
#include <iomanip>
#include <cassert>
#include <bitset>
using namespace std;

typedef pair<int, int> P;
typedef pair<int, P> P2;
#define rep(i, n) for (int i=0; i<(n); i++)
#define all(c) (c).begin(), (c).end()
#define uniq(c) c.erase(unique(all(c)), (c).end())
#define _1 first
#define _2 second
#define pb push_back
#define INF 1145141919
#define MOD 1000000007

int N, M;
int U[100000], R[100000];

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

void unite(int x, int y) {
  x = find(x), y = find(y);
  if (x == y) return;
  if (R[x] < R[y]) swap(x, y);
  U[y] = x;
  R[x] += R[y];
  R[y] = 0;
}

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

signed main() {
  ios::sync_with_stdio(false); cin.tie(0);
  while (cin >> N >> M) {
    if (N == 0 && M == 0) break;
    vector<P2> edges;
    rep(i, M) {
      int a, b, c;
      cin >> a >> b >> c;
      edges.pb(P2(c, P(a, b)));
    }
    sort(all(edges));
    for (int i=0; i<N; i++) U[i] = i, R[i] = 1;
    int s = 0;
    for (P2 e : edges) {
      int a = e._2._1, b = e._2._2;
      if (!same(a, b)) {
        s += e._1;
        unite(a, b);
      }
    }
    cout << s << "\n";
  }
  return 0;
}