kruskal最小生成树

https://vjudge.net/problem/hdu-1863


kruskal 算法是根据边来进行一条一条地往生成树中添加的,然后只有边的两点属于不同集合的边才能加入生成树中;


想过用vis数组标记然后进行看是否都用过了,如果都用过了,就不加入生成树中;后面想想是我想错了,如果出现两个最小树的情况,如果不把这两个树连在一起的话就不是最小生成树了;


#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll maxn = 1000 + 10;
int n,m;
struct Node
{
	int x,y,z;
}a[maxn];
bool cmp(const Node &x,const Node &y)
{
	return x.z < y.z;
}
int fa[maxn];
void Init()
{
	for(int i = 0; i< maxn; i ++)
	fa[i] = i;
}
int finds(int x)
{
	return x == fa[x] ? x : (fa[x] = finds(fa[x]));
}
int main()
{
	while( ~ scanf("%d%d",&n,&m) && n)
	{
		
		for(int i = 1; i <= n; i ++)
		{
			scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);
		}
		Init();
		sort(a+1,a+n+1,cmp);
		int ans = 0;
		int cnt = 0;
		for(int i = 1; i <= n; i ++)
		{
			int x = finds(a[i].x);
			int y = finds(a[i].y);
			if(x != y)
			{
				fa[x] = y;
				ans += a[i].z;
				cnt ++;
			}
			if(cnt == m - 1)
			{
				cout << ans << endl;
				break;
			}
		}
		if(cnt != m - 1)
		cout << "?" << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值