Prim
//============================================================================
// Name : hello.cpp// Author : key
// Version : 8
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
#define NUM_INF 0x7FFFFFFF
int vis[70];
int lowc[70];
int cost[70][70];
int prim(int n) // vertex: 0 ~ n-1
{
int i, j, p;
int minc, res = 0;
memset(vis, 0, sizeof(vis));
vis[0] = 1;
for (i=1; i<n; i++)
lowc[i] = cost[0][i];
for (i=1; i<n; i++)
{
minc = NUM_INF; p = -1;
for (j=0; j<n; j++)
{
if (0 == vis[j] && minc > lowc[j])
{
minc = lowc[j]; p = j;
}
}
if (NUM_INF == minc)
return -1; // 原圖不連通
res += minc; vis[p] = 1;
for (j=0; j<n; j++)
{
if (0 == vis[j] && lowc[j] > cost[p][j])
{
lowc[j] = cost[p][j];
}
}
}
return res;
}
int main()
{
int n;
int t;
int a,b,c;
int i,j;
while(scanf("%d",&n)!=EOF&&n)
{
for(i=0;i<n;i++)
for(j=0;j<n;j++)
cost[i][j] = NUM_INF;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&a,&b,&c);
a--;
b--;
if(cost[a][b]>c)
{
cost[a][b] = c;
cost[b][a] = c;
}
}
printf("%d\n",prim(n));
}
return 0;
}