题目:
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXV=100;
const int MAXE=10010;
//边集定义
struct edge
{
int u,v;
int cost;
} E[MAXE];
bool cmp(edge a,edge b)
{
return a.cost<b.cost;
}
//并查集定义
int father[MAXV];
int findFather(int x)
{
int a=x;
while(x!=father[x])
{
x=father[x];
}
while(a!=father[a])
{
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
int kruskal(int n,int m)
{
int ans=0,num_edge=0;
for(int i=0; i<n; i++)
{
father[i]=i;
}
sort(E,E+m,cmp);
for(int i=0; i<m; i++) //枚举边
{
int faU=findFather(E[i].u);
int faV=findFather(E[i].v);
if(faU!=faV)
{
father[faU]=faV;
ans+=E[i].cost;
num_edge++;
if(num_edge==n-1)
break;
}
}
if(num_edge!=n-1)
return -1;
else
return ans;
}
int main()
{
int N;
while((cin>>N)&&N!=0)
{
int t=N*(N-1)/2;
for(int i=0; i<t; i++)
{
cin>>E[i].u;
cin>>E[i].v;
cin>>E[i].cost;
}
int ans=kruskal(N,t);
cout << ans << endl;
}
return 0;
}