Agri-Net的Kruskal算法+并查集实现(按大小合并+路径压缩)

本文详细解析了Kruskal算法结合并查集实现最小生成树的过程,包括算法复杂度分析及代码实现。Kruskal算法通过排序所有边并依次尝试加入最小权重的边来构建最小生成树,使用并查集进行高效的合并操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Agri-Net的Kruskal算法+并查集实现

算法复杂度分析

    对所有的边进行排序,排序复杂度为O(mlogm),随后对边进行合并,合并使用并查集,并查集使用link by size的方式实现,同时在find函数实现了路径压缩。每个元素第一次被执行find操作需要的复杂度为O(logm),总共m个元素,可以在循环中设置,如果已经有n-1条边,那么可以停止循环,时间复杂度为O(nlogm),前后两个步骤的时间复杂度为O(mlogm+nlogm) ,而存在最小生成树中的情况下,图至少有n-1条边,即m>=n-1,于是整体复杂度为O(mlogn)。即使对并查集做了路径压缩的优化,但是前面的排序过程仍然是算法的瓶颈,因此算法复杂度仍然是O(mlogn)。

代码实现

#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
// 边
struct Edge {
	int from, to;
	int weight;
	Edge(int f, int t, int w) :from(f), to(t), weight(w) {}
	bool operator <(const Edge& e)const { return this->weight < e.weight; }
};

// 并查集
struct QuickUnion {
	vector<int> sz; // 表示集合大小的数组
	vector<int> parent; // 表示一个顶点的所在集合的根节点
	QuickUnion(const int n) {
		sz.assign(n,0);
		for (int i = 0; i < n; ++i)
			parent.push_back(i);
	}
	// 寻找一个节点的根节点
	int find(const int x) {
		if (x != parent[x])
			parent[x] = find(parent[x]);// 路径压缩
		return parent[x];
	}
	// 合并两个节点所在的集合
	bool unionNode(const int x, const int y) {
		int p1 = find(x);
		int p2 = find(y);
		if (p1 == p2)
			return false;
		if (sz[p1] >= sz[p2]){
			sz[p1] += sz[p2];
			parent[p2] = p1;
		}
		else{
			sz[p2] += sz[p1];
			parent[p1] = p2;
		}
		return true;
	}
};

int Kruskal(vector<Edge> graph, int nodeNum) {
	QuickUnion qu(nodeNum);
	sort(graph.begin(),graph.end());
	int MSTWeight = 0;
	int edgeCount = 0;
	for (auto&e : graph){
		if (qu.unionNode(e.from, e.to)){
			MSTWeight += e.weight;
			++edgeCount;
			if (edgeCount == nodeNum - 1)
				break;
		}
	}
	return MSTWeight;
}

int main() {
	int edgeLen;
	while (scanf("%d",&edgeLen)!=EOF){
		vector<Edge > graph;
		int curRow = 0, curCol = 0;
		while (curRow < edgeLen){
			curCol = 0;
			while (curCol < edgeLen){
				int tmp;
				scanf("%d", &tmp);
				if (curRow < curCol)
					graph.emplace_back(curRow, curCol, tmp);
				curCol++;
			}
			++curRow;
		}
		printf("%d\n", Kruskal(graph,edgeLen));
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值