51nod:1212 无向图最小生成树

基准时间限制: 1 秒 空间限制: 131072 KB 分值: 0 难度:基础题
收藏
关注
取消关注
N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。
Input
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000)
第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
Output
输出最小生成树的所有边的权值之和。
Input示例
9 14
1 2 4
2 3 8
3 4 7
4 5 9
5 6 10
6 7 2
7 8 1
8 9 7
2 8 11
3 9 2
7 9 6
3 6 4
4 6 14
1 8 8
Output示例

37


解题思路:用克鲁斯卡尔算法就行(很久没写了,有点生-,-)


代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;
int fa[1010];
struct node
{
	int u,v,power;
}bian[50010];
bool cmp(struct node a,struct node b)
{
	return a.power<b.power;
}
int find(int x)
{
	int r=x;
	while(r!=fa[r])
	{
		r=fa[r];
	}
	return r;
}
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{
		fa[i]=i;
	}
	for(int i=0;i<m;i++)
	{
		int s,e,w;
		scanf("%d%d%d",&s,&e,&w);
		bian[i].u=s;
		bian[i].v=e;
		bian[i].power=w;
	}
	sort(bian,bian+m,cmp);
	int sum=0;
	for(int i=0;i<m;i++)
	{
		int s,e,w;
		s=bian[i].u;
		e=bian[i].v;
		w=bian[i].power;
		int fx=find(s),fy=find(e);
		if(fx!=fy)
		{
			fa[fx]=fy;//很久没写这里刚开始写成了fa[s]=e;。。。这样写错的话原来的s就与之前的集合断了联系,画个图就明白了 
			sum=sum+w;
		}
	}
	printf("%d\n",sum);
	return 0;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值