#include <stdio.h>
#include<iostream>
#include <string.h>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
#include <set>
#include <queue>
using namespace std;
const int maxn = 110;
const int MaxL = 5000;
int father[maxn];
typedef struct edge {
int a, b;//两个顶点
int w;//边的权重
}edge;
bool cmp(edge e1, edge e2)
{
return e1.w < e2.w;
}
int FindRoot(int s)
{
while (s != father[s])
s = father[s];
return s;
}
int main()
{
int n;
while (cin >> n && n != 0)
{
for (int i = 0; i<n; i++)
father[i] = i;
edge E[MaxL];
for (int i = 0; i<n*(n-1)/2; i++)
scanf("%d%d%d", &E[i].a, &E[i].b, &E[i].w);
sort(E, E + n * (n - 1) / 2, cmp);
int a, b, roota, rootb, res = 0;
for (int i = 0; i<n*(n - 1) / 2; i++)
{
a = E[i].a;
b = E[i].b;
roota = FindRoot(a);
rootb = FindRoot(b);
if (roota != rootb)
{
father[roota] = rootb;//此处千万不能将a,b合并,否则集合会合并失败
res += E[i].w;
}
}
printf("%d\n", res);
}
return 0;
}
畅通工程问题
最新推荐文章于 2022-11-05 18:12:20 发布