#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXV = 1005;
const int MAXE = 50005;
const int INF = 0x3f3f3f3f;
int cost[MAXV][MAXV];
int mincost[MAXV];
bool used[MAXV];
int V,E;
/*prim适用于边多点少,复杂度为O(V*V)*/
int prim(){
for (int i = 0; i < V; ++i){
mincost[i] = INF;
used[i] = false;
}
mincost[0] = 0;
int res = 0;
while (true){
int v = -1;
for (int u = 0; u < V; ++u){ //从不属于集合x中的点选取x到其权值最小的点
if (!used[u] && (v == -1 || mincost[u] < mincost[v])) v = u;
}
if (v == -1) break;
used[v] = true;
res += mincost[v];
for (int u = 0; u < V; ++u){
mincost[u] = min(mincost[u],cost[v][u]);
}
}
return res;
}
int main(){
int x,y,z;
while (scanf("%d%d",&V,&E)!=EOF){
for (int i = 0; i < V; ++i){
for (int j = 0; j < V; ++j){
if (i != j)
cost[i][j] = INF;
}
}
for (int i = 0; i < E; ++i){
scanf("%d%d%d",&x,&y,&z);
x -= 1 ,y -= 1; //点从1到n
if (cost[x][y] == INF || (cost[x][y]!=INF && cost[x][y] > z)){ //判断是否有重边,有就更新最小值
cost[x][y] = z;
cost[y][x] = z;//无向图 ,正反都来一遍
}
}
int ans = prim();
printf("%d\n",ans);
}
return 0;
}
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1005;
int V,E;
struct node{
int to,w;
bool operator < (const node &b)const{
return w > b.w;
} //w越小的优先级越高,保证在优先队列里取出的第一个的w最小
};
vector<node> spot[MAXN];
bool vis[MAXN];
priority_queue<node > q;
int prim(){
while (!q.empty()) q.pop();
memset(vis,false,sizeof(vis));
int res = 0;
for (int i = 0; i < spot[V].size(); ++i){ //取一个起点
q.push(spot[V][i]);
}
vis[V] = true;
node temp;
for (int i = 0; i < V-1; ++i){
temp = q.top(); q.pop();
while (vis[temp.to]){
temp = q.top();
q.pop();
}
res += temp.w;
vis[temp.to] = true;
for (int j = 0; j < spot[temp.to].size(); ++j){//处理选择的点能到达的所有的点(且未被访问)
if (!vis[ spot[temp.to][j].to ]){
q.push(spot[temp.to][j]);
}
}
}
return res;
}
int main(){
while (scanf("%d%d",&V,&E)!=EOF){
int x,y,z;
for (int i = 0; i < E; ++i){
scanf("%d%d%d",&x,&y,&z);
node temp;
temp.to = y;temp.w = z;
spot[x].push_back(temp);
temp.to = x;
spot[y].push_back(temp);
}
int ans = prim();
printf("%d\n",ans);
}
return 0;
}
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=10005;
struct node { int from,to,len;} edge[maxn];//储存边的数据结构
int n,fa[maxn],m,ans,q;
bool cmp(node a,node b) { return a.len<b.len; }//边按从小到大的顺序排列
int Find(int x)
{
if(fa[x]==x) return x;
return fa[x]=Find(fa[x]);
}
void Merge(int x,int y)
{
x=Find(x),y=Find(y);
if(x!=y) fa[y]=x;
}
int kruskal()
{
sort(edge,edge+m,cmp);//边排序
for(int i=0;i<=n;i++) fa[i]=i;//初始化并查集
ans=0;
for(int i=0;i<m;i++)//一条边的两个端点不在同一个集合,则选它,并合并端点
if(Find(edge[i].from)!=Find(edge[i].to)) Merge(edge[i].from,edge[i].to),ans+=edge[i].len;
return ans;
}
int main()
{
while(cin>>n>>m,n)
{
for(int i=0;i<m;i++) cin>>edge[i].from>>edge[i].to>>edge[i].len;
cout<<kruskal()<<endl;
}
return 0;
}