题干
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int set[10001];
void InitDisjointSet(int n) {
for(int i = 0; i<n; ++i) {
set[i] = i;
}
}
int FindDisjointSet(int u) {
if(u == set[u]) {
return u;
} else {
set[u] = FindDisjointSet(set[u]);
return set[u];
}
}
int UnionDisjointSet(int u,int v) {
int uRoot = FindDisjointSet(u);
int vRoot = FindDisjointSet(v);
set[vRoot] = uRoot;
}
struct Edge{
int u;
int v;
int weight;
Edge(int _u,int _v,int _weight){
u = _u;
v = _v;
weight = _weight;
}
};
bool compare(Edge lhs,Edge rhs){
return lhs.weight < rhs.weight;
}
int main()
{
int n;
while(scanf("%d",&n) != EOF){
if(n == 0){
break;
}
vector<Edge> edgeVec;
InitDisjointSet(n+1);
for(int i = 0; i<(n-1)*n/2; ++i){
int u,v,weight;
scanf("%d%d%d",&u,&v,&weight);
Edge e(u,v,weight);
edgeVec.push_back(e);
}
sort(edgeVec.begin(),edgeVec.end(),compare);
int totalWeight = 0;
int curEdgeNum = 0;
for(int i = 0;i< edgeVec.size();++i){
int u = edgeVec[i].u;
int v = edgeVec[i].v;
int weight = edgeVec[i].weight;
if(FindDisjointSet(u) != FindDisjointSet(v)){
UnionDisjointSet(u,v);
++curEdgeNum;
totalWeight += weight;
if(curEdgeNum == n-1){
break;
}
}
}
printf("%d\n",totalWeight);
}
return 0;
}