#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
int u, v, weight;
};
struct Node {
int parent, rank, size;
};
// 按照边权重从小到大排序
bool compareEdges(const Edge& a, const Edge& b) {
return a.weight < b.weight;
}
// 查找节点的根节点
int findRoot(vector<Node>& nodes, int i) {
if (nodes[i].parent != i) {
nodes[i].parent = findRoot(nodes, nodes[i].parent);
}
return nodes[i].parent;
}
// 合并两个集合
void unionSets(vector<Node>& nodes, int xRoot, int yRoot) {
if (nodes[xRoot].rank < nodes[yRoot].rank) {
nodes[xRoot].parent = yRoot;
nodes[yRoot].size += nodes[xRoot].size;
} else if (nodes[xRoot].rank > nodes[yRoot].rank) {
nodes[yRoot].parent = xRoot;
nodes[xRoot].size += nodes[yRoot].size;
} else {
nodes[yRoot].parent = xRoot;
nodes[xRoot].rank++;
nodes[xRoot].size += nodes[yRoot].size;
}
}
// 构建Kruskal重构树
vector<Edge> buildReconstructionTree(vector<Edge>& edges, int n) {
vector<Node> nodes(n);
for (int i = 0; i < n; i++) {
nodes[i].parent = i;
nodes[i].rank = 0;
nodes[i].size = 1;
}
sort(edges.begin(), edges.end(), compareEdges);
vector<Edge> result;
for (const auto& edge : edges) {
int xRoot = findRoot(nodes, edge.u);
int yRoot = findRoot(nodes, edge.v);
if (xRoot != yRoot) {
result.push_back(edge);
unionSets(nodes, xRoot, yRoot);
}
}
return result;
}
int main() {
int n = 6;
vector<Edge> edges = {{0, 1, 4}, {0, 2, 2}, {1, 2, 1}, {2, 3, 5}, {3, 4, 3}, {3, 5, 2}, {4, 5, 1}};
vector<Edge> reconstructionTree = buildReconstructionTree(edges, n);
cout << "Edges in the Kruskal Reconstruction Tree:" << endl;
for (const auto& edge : reconstructionTree) {
cout << edge.u << " - " << edge.v << ", Weight: " << edge.weight << endl;
}
return 0;
}
Kruskal重构树
解释
在这个示例中,我们定义了一个边(Edge)结构体来表示图的边,以及一个节点(Node)结构体来表示Kruskal重构树中的节点,其中包含了节点的父节点、秩和大小。然后,我们使用Kruskal算法对边按权重进行排序,并使用并查集数据结构来构建Kruskal重构树。最后,我们输出Kruskal重构树中的边。