最小生成树(kruskal算法)

#include<bits/stdc++.h>
using namespace std;

struct node
{
	int x, y, z;
}s[200010];
int q[100010];

bool cmp(node a, node b)
{
	return a.z < b.z;
}

int ffind(int x)
{
    if(q[x]!=x){
        return q[x]=ffind(q[x]);
    }else{
        return q[x];
    }
}
void com(int x, int y)
{
    int xx = ffind(x);
    int yy = ffind(y);
    q[yy] = xx;
}

int main()
{
	int n, m;
	cin >> n >> m;
	for(int i = 1; i <= n; i++) q[i] = i;
	for(int i = 0; i < m; i++) cin >> s[i].x >> s[i].y >> s[i].z;
	sort(s,s+m,cmp);
	int k = 1;
	int sum = 0;
	for(int i = 0; i < m; i++){
		if(k==n) break;
		int v1 = s[i].x;
		int v2 = s[i].y;
		if(ffind(v1)!=ffind(v2)){
			com(v1,v2);
			k++;
			sum += s[i].z;
		}
	}
	cout << sum << endl;
	return 0;
}
/*
5 6
2 1 3
2 4 7
1 3 4
3 4 8
4 5 13
1 5 9

23
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值