Python实现Kruskal算法:基于不相交集数据结构的最小生成树求解
Here's an implementation of Kruskal's algorithm using a disjoint-set data structure implemented with trees in Python: ```python class DisjointSet: def __init__(self, vertices): self.rank = {u: 0 for u in vertices} self.parent = {u: u for u in vertices} def find(self, u): if self.parent[u] != u: self.parent[u] = self.find(self.parent[u]) return self.parent[u] def union(self, u, v): root_u = self.find(u) root_v = self.find(v) if root_u != root_v: if self.rank[root_u] < self.rank[root_v]: self.parent[root_u] = root_v else: self.parent[root_v] = root_u if self.rank[root_u] == self.rank[root_v]: self.rank[root_u] += 1 def makeset(self, u): self.rank[u] = 0 self.parent[u] = u def sortededges(graph): edges = [(weight, u, v) for u, connections in graph.items() for v, weight in connections.items()] edges.sort() mst = [] ds = DisjointSet(list(graph.keys())) for weight, u, v in edges: root_u = ds.find(u) root_v = ds.find(v) if root_u != root_v: mst.append((weight, u, v)) ds.union(u, v) return mst # Example usage: graph = { 'A': {'B': 7, 'D': 5}, 'B': {'A': 7, 'C': 8, 'D': 9}, 'C': {'B': 8, 'D': 15, 'E': 10}, 'D': {'A': 5, 'B': 9, 'C': 15, 'E': 6}, 'E': {'C': 10, 'D': 6}, } mst = sortededges(graph) print("Minimum Spanning Tree edges:", mst) ``` This code defines a `DisjointSet` class that implements the required operations (`makeset`, `find`, and `union`) using trees. The `sortededges` function takes a graph represented as a dictionary and returns the edges of the minimum spanning tree using Kruskal's algorithm. In this implementation, the graph is assumed to be undirected. ######[AI写代码神器 | 531点数解答 | 2023-12-29 16:59:27]
- Python 实战:学生信息列表转字典、遍历、深拷贝及数据修改全流程(GPT | 422点数解答 | 2024-10-29 15:43:54)414
- Python实战:学生成绩列表转字典,深拷贝与数据修改操作全解析(字节豆包 | 254点数解答 | 2024-10-29 16:01:39)405
- 代码填空挑战:完成正态分布、随机数生成及数据处理代码(阿里通义 | 506点数解答 | 2025-03-23 14:32:14)317
- 挑战!完成代码填空解锁数据处理奥秘(字节豆包 | 116点数解答 | 2025-03-26 22:22:15)335
- 挑战填空!完成这段 NumPy 代码实现数据生成与保存(DeepSeek | 178点数解答 | 2025-03-26 22:26:30)396
- Python 运行报错:urllib3 网络连接创建失败,原因及排查建议(字节豆包 | 161点数解答 | 2024-10-31 00:39:36)458
- C语言实现多班级学生信息管理系统:含增删改查与多样排序功能(GPT | 2547点数解答 | 2024-12-15 22:08:58)357
- C语言实现学生信息管理系统:含增删改查与多种排序功能(GPT | 6408点数解答 | 2024-12-15 22:10:03)348
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)343
- Python实现:基于不相交集数据结构的Kruskal算法课程实验( | 1636点数解答 | 2023-12-29 16:57:35)395
- Python实现Kruskal算法:基于不相交集数据结构的最小生成树求解(阿里通义 | 531点数解答 | 2023-12-29 16:59:27)356
- 旅行售货员问题:详细步骤剖析与贪心算法Python代码实现(字节豆包 | 444点数解答 | 2024-12-17 03:32:59)275