HDU 1233(还是畅通工程)
作者:互联网
计算最小生成树的总长度,使用 Kruskal算法。
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 100;
int father[MAXN]; //父结点
struct road //公路
{
int start; //起点
int end; //终点
int dis; //距离
}r[MAXN * MAXN];
//排序条件
bool cmp(road r1, road r2)
{
return r1.dis < r2.dis;
}
//初始化并查集
void makeSet(int n)
{
for (int i = 1; i <= n; i++)
father[i] = i;
}
//查找x所在集合的代表元素(所在树的根结点)
int find(int x)
{
if (x != father[x])
father[x] = find(father[x]);
return father[x];
}
int main()
{
int N;
while (scanf("%d", &N) != EOF)
{
if (N == 0)
break;
makeSet(N);
int n = N * (N - 1) / 2;
for (int i = 0; i < n; i++)
{
scanf("%d %d %d", &r[i].start, &r[i].end, &r[i].dis);
}
sort(r, r + n, cmp);
int sum = 0; //总距离
for (int i = 0; i < n; i++)
{
int fx = find(r[i].start);
int fy = find(r[i].end);
if (fx != fy)
{
father[fx] = fy;
sum += r[i].dis;
}
}
printf("%d\n", sum);
}
return 0;
}
继续加油。
标签:HDU,r2,1233,int,MAXN,畅通,include,road,dis 来源: https://blog.csdn.net/Intelligence1028/article/details/104702794