Python实现:基于不相交集数据结构的Kruskal算法课程实验
Sure! Here's an example implementation of Kruskal's algorithm using a disjoint-set data structure in Python: ```python class DisjointSet: def __init__(self, size): self.parent = [i for i in range(size)] self.rank = [0] * size 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): root1 = self.find(u) root2 = self.find(v) if self.rank[root1] < self.rank[root2]: self.parent[root1] = root2 elif self.rank[root1] > self.rank[root2]: self.parent[root2] = root1 else: self.parent[root2] = root1 self.rank[root1] += 1 def sortededges(vertices, edges): edges.sort(key=lambda x: x[2]) # Sort edges by weight in ascending order mst = [] ds = DisjointSet(vertices) # Create a disjoint-set data structure for u, v, weight in edges: if ds.find(u) != ds.find(v): # Check if adding the edge creates a cycle mst.append((u, v, weight)) # Add the edge to the minimum spanning tree ds.union(u, v) # Merge the sets of u and v return mst ``` To use this implementation, you need to provide the number of vertices (`vertices`) and a list of edges (`edges`), where each edge is represented as a tuple `(u, v, weight)`. Please note that this is a basic implementation and there are alternative ways to implement a disjoint-set data structure. Depending on your specific requirements and constraints, you may need to make modifications to the code. ######[AI写代码神器 | 1636点数解答 | 2023-12-29 16:57:35]
- Python 实战:学生信息列表转字典、遍历、深拷贝及数据修改全流程(GPT | 422点数解答 | 2024-10-29 15:43:54)414
- Python实战:学生成绩列表转字典,深拷贝与数据修改操作全解析(字节豆包 | 254点数解答 | 2024-10-29 16:01:39)405
- C++实现单门课程成绩管理系统:教师学生双身份操作全解析(GPT | 6361点数解答 | 2024-05-24 02:01:02)534
- C++ 实现超实用单门课程成绩管理系统,教师学生灵活使用! (GPT | 68点数解答 | 2024-05-24 10:17:09)330
- C++实现:功能完备的单门课程成绩管理系统(GPT | 4293点数解答 | 2024-05-24 10:20:03)376
- 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)394
- Python实现Kruskal算法:基于不相交集数据结构的最小生成树求解(阿里通义 | 531点数解答 | 2023-12-29 16:59:27)355
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)310