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

版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/t46414704152abc/article/details/83896339

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;
}

猜你喜欢

转载自blog.csdn.net/t46414704152abc/article/details/83896339