HOJ 1233 还是畅通工程(最小生成树,水题)

62 篇文章 0 订阅
41 篇文章 0 订阅

最小生成树,水题
本题要点:
1、套用 prim 模板即可。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MaxN = 110, MaxM = 10010;
int fa[MaxN];
int n, m;
bool vis[MaxN];

struct rec
{
	int x, y, z;
	bool operator<(const rec& rhs) const
	{
		return z < rhs.z;
	}
}edge[MaxM];

int get(int x)
{
	if(fa[x] == x)
		return x;
	return fa[x] = get(fa[x]);
}

int main()
{
	while(scanf("%d", &n) != EOF && n)
	{
		for(int i = 1; i <= n; ++i)
			fa[i] = i;
		m = n * (n - 1) / 2;
		for(int i = 1; i <= m; ++i)
		{
			scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].z);
		}
		int ans = 0;
		sort(edge + 1, edge + m + 1);
		for(int i = 1; i <= m; ++i)
		{
			int x = get(edge[i].x), y = get(edge[i].y);
			if(x == y)	continue;
			fa[x] = y;
			ans += edge[i].z;
		}
		printf("%d\n", ans);
	}
	return 0;
}

/*
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
*/

/*
3
5
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值