#include <iostream> #include <algorithm> #include <cstdio> #include <string> #include <cstring> #include <cstdlib> #include <map> #include <vector> #include <set> #include <queue> #include <stack> #include <cmath> using namespace std; #define mem(s,t) memset(s,t,sizeof(s)) #define pq priority_queue #define pb push_back #define fi first #define se second #define ac return 0; #define TLE std::ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cout.precision(10); const int mxn = 1e3; int root[mxn]; int n,m,k,l,r,t,ans,cnt; struct node { int x,y,k; bool operator <(const node &a) const { return k<a.k; } }no[50+5]; void init() {for(int i=0;i<=mxn;i++) root[i]=i;} int Judge(int now) { if( now==root[now] ) return now; root[now] = Judge(root[now]); return root[now]; } int check(int x,int y) { if(Judge(x)==Judge(y)) return 0; root[Judge(x)]=Judge(y); return 1; } int main() { TLE; while(cin>>n&&n) { cin>>m; init(); ans = 0,cnt = 0 ; for(int i=1;i<=m;i++) cin>>no[i].x>>no[i].y>>no[i].k; sort(no+1,no+1+m); for(int i=1;i<=m;i++) { if( check( no[i].x,no[i].y ) ) { cnt++; ans += no[i].k; } if(cnt==n-1) break; } cout<<ans<<endl; } return 0; }