算法导论-第23章-最小生成树:Kruskal算法(基于按秩合并、路径压缩的不相交集合)C++实现

本文详细介绍了Kruskal算法的实现过程,包括元素集合、并查集、边权重排序及最小生成树构建步骤,通过输入顶点数量和边信息,输出最小生成树的边集合。

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

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

static char elements_index{ 'a' };
using P = pair<char, char>;
using PP = pair<P, int>;

struct Element {
	char index{ elements_index++ };
	int rank{ 0 };
	Element* parent{ this };
};


Element* FIND_SET(Element* x) {
	if (x != x->parent) {
		x->parent = FIND_SET(x->parent);
	}
	return x->parent;
}

void LINK(Element* x, Element* y) {
	if (x->rank > y->rank) {
		y->parent = x;
	}
	else {
		x->parent = y;
		if (x->rank == y->rank) {
			y->rank++;
		}
	}
}

void UNION(Element* x, Element* y) {
	LINK(FIND_SET(x), FIND_SET(y));
}

vector<P> MST_KRUSKAL(vector<PP>& v, Element* E) {
	vector<P> A{};
	for (auto edge : v) {
		if (FIND_SET(&E[edge.first.first - 'a']) != FIND_SET(&E[edge.first.second - 'a'])) {
			A.push_back({ edge.first.first, edge.first.second });
			UNION(&E[edge.first.first - 'a'], &E[edge.first.second - 'a']);
		}
	}
	return A;
}

int main(int argc, char* argv[]) {

	size_t vertex_size{};
	cout << "please input the numbers of vertex :" << endl;
	cin >> vertex_size;
	vector <PP> v{};
	char v0{};
	char v1{};
	int weight{};
	cout << "please input the edge as : v0 v1 weight( end up with 0 0 0 )" << endl;
	while (true) {
	cout << "edge :" << endl;
	cin >> v0 >> v1 >> weight;
	if (v0 == '0' || v1 == '0' || weight == 0) {
	break;
	}
	P p{ v0, v1 };
	PP pp{ p, weight };
	v.push_back(pp);
	}
	sort(v.begin(), v.end(), [](const PP& x, const PP& y){ return x.second < y.second; });
	Element* E = new Element[vertex_size]{};
	vector<P> result = MST_KRUSKAL(v, E);
	cout << "MST has edges as follow :" << endl;
	for (auto a : result) {
		cout << a.first << "  " << a.second << endl;
	}
	delete[]E;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值