hiho1098 : 最小生成树·Kruscal算法

复习最小生成树Kruscal算法。和prime算法相比,Kruscal算法更适合顶点多、边少的稀疏图。prime相对适合顶点偏少的情况

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
int father[100005]; // father[i]代表 i 节点的父节点
struct edge { // 边的定义
	int x, y, w;
	edge() {}
	edge(int x, int y, int w) : x(x), y(y), w(w) {}
	bool operator < (const edge& oth) const {
		return w <= oth.w;
	}
	
};

int find_root(int x) { // 找到 节点 x 所在树的根节点
	while (x != father[x])
		x = father[x];
	return x;
}

void  uni(int x, int y) { // 将 x节点所在树与 y 节点所在树合并
	int root_x = find_root(x);
	int root_y = find_root(y);
	father[root_x] = root_y;

}
int main() {
	int N, M;
	while (cin >> N >> M) {
		int x, y, w;
		vector<edge> a;
		for (int i = 0; i < M; ++i) { // 读入M条边
			cin >> x >> y >> w;
			a.push_back(edge(x, y, w));
		}
		for (int i = 1; i <= N; ++i) //初始化每一个节点是一颗树 
			father[i] = i;
		sort(a.begin(), a.end()); // 按照边的权值 从小到大排序
		int ans = 0;
		for (edge e : a) { // 当边的两个节点 在不同的树中时,合并
			if (find_root(e.x) == find_root(e.y)) continue;
			ans += e.w;
			uni(e.x, e.y);

		}
		cout << ans << endl;
	}
	return 0;
	
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值