c++实现_Kruskal算法(最小生成树算法)

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

using namespace std;
typedef pair<int, int> iPair;
struct Graph {
	int V, E;//V:the number of the vertices
			 //E:the number of edges
	vector<pair<int, iPair>> edges;

	Graph(int V, int E) {
		this->V = V;
		this->E = E;
	}
	void addEdge(int x, int y, int w) {
		edges.push_back({w,{x,y}});
	}
	int caculate_mst();
};
struct disjointSets {
	vector<int> parent, rank;
	int n;
	disjointSets(int n){
		this->n = n;
		parent = vector<int>(n, -1);
		rank = vector<int>(n, -1);
	}
	int find_root(int x) {
		int x_root = x;
		while (parent[x_root] != -1)
			x_root = parent[x_root];
		return x_root;
	}
	bool union_vertices(int x, int y) {
		int x_root = find_root(x);
		int y_root = find_root(y);
		if (x_root == y_root)
			return false;
		else {
			if (rank[x_root] > rank[y_root])
				parent[y_root] = x_root;
			else if (rank[y_root] > rank[x_root])
				parent[x_root] = y_root;
			else {
				parent[x_root] = y_root;
				rank[y_root] += 1;
			}
		}
		return true;
	}
};
int Graph::caculate_mst() {
	int mst = 0;
	disjointSets ds(V);
	sort(edges.begin(), edges.end());
	for (auto it = edges.begin(); it != edges.end(); it++) {
		int x = it->second.first;
		int y = it->second.second;
		int x_root = ds.find_root(x);
		int y_root = ds.find_root(y);
		if (ds.union_vertices(x_root, y_root)) {
			cout << x << "-" << y << endl;
			mst += it->first;
		}
	}
	return mst;
}
int main() {
	int V = 9, E = 14;
	Graph g(V, E);
	
	g.addEdge(0, 1, 4);
	g.addEdge(0, 7, 8);
	g.addEdge(1, 2, 8);
	g.addEdge(1, 7, 11);
	g.addEdge(2, 3, 7);
	g.addEdge(2, 8, 2);
	g.addEdge(2, 5, 4);
	g.addEdge(3, 4, 9);
	g.addEdge(3, 5, 14);
	g.addEdge(4, 5, 10);
	g.addEdge(5, 6, 2);
	g.addEdge(6, 7, 1);
	g.addEdge(6, 8, 6);
	g.addEdge(7, 8, 7);


	int mst = g.caculate_mst();
	cout << "mst=" << mst;
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值