cruskal算法求最小支撑树 打印支撑树的边集合 带图例

克鲁斯卡尔算法通过按权值排序边并逐步添加边来构造最小支撑树,避免形成环路。该过程涉及不相交集数据结构,包含合并和查找操作,后者实行路径压缩。代码实现后,附带了测试数据和运行结果的图例展示。
摘要由CSDN通过智能技术生成

cruskal算法的思想很简单,就是把所有边按权值大小排序,由小到大,然后依次选一条边,如果这条边加入最小支撑树中不会造成回路,就把这条边加进去,否则取下一条边继续探测。如果这个图有 n 个顶点,则选出 n-1 条边即可。


思想很简单,可实现却涉及到一种特殊的数据结构,叫不相交集

这种集合有两个主要的操作,一个是合并,就是将两个元素合并到这个集合中,合并时按秩合并的,秩大的作为秩小的父节点。

一个叫查找,就是返回这个元素的父节点,查找 的时候会执行路径压缩,也就是所,如果 a 是 b 的父节点, b 又是 c 的父节点, c 又是 d 的父节点,这样查找 d 的父节点时,返回的是 d 的最终根节点,也就是 a, 同时会把 d 到  a 上的所有节点的父节点都置为 a。

代码如下

#include <iostream>
#include <vector>
#include <algorithm>
using n
可以直接回答,以下是CSharp实现Cruskal算法的示例代码: ```csharp using System; using System.Collections.Generic; public class Graph { public int V, E; public List<Edge> edges; public Graph(int v, int e) { V = v; E = e; edges = new List<Edge>(E); for (int i = 0; i < E; ++i) edges.Add(new Edge()); } public int Find(int[] parent, int i) { if (parent[i] == -1) return i; return Find(parent, parent[i]); } public void Union(int[] parent, int x, int y) { int xset = Find(parent, x); int yset = Find(parent, y); parent[xset] = yset; } public void KruskalMST() { Edge[] result = new Edge[V]; int e = 0; int i = 0; edges.Sort(); int[] parent = new int[V]; for (int j = 0; j < V; ++j) parent[j] = -1; while (e < V - 1) { Edge next_edge = edges[i++]; int x = Find(parent, next_edge.src); int y = Find(parent, next_edge.dest); if (x != y) { result[e++] = next_edge; Union(parent, x, y); } } Console.WriteLine("Following are the edges in " + "the constructed MST"); for (i = 0; i < e; ++i) Console.WriteLine(result[i].src + " - " + result[i].dest + ": " + result[i].weight); } } public class Edge : IComparable<Edge> { public int src, dest, weight; public int CompareTo(Edge other) { return weight.CompareTo(other.weight); } } public class Test { public static void Main() { int V = 4; int E = 5; Graph graph = new Graph(V, E); graph.edges[0].src = 0; graph.edges[0].dest = 1; graph.edges[0].weight = 10; graph.edges[1].src = 0; graph.edges[1].dest = 2; graph.edges[1].weight = 6; graph.edges[2].src = 0; graph.edges[2].dest = 3; graph.edges[2].weight = 5; graph.edges[3].src = 1; graph.edges[3].dest = 3; graph.edges[3].weight = 15; graph.edges[4].src = 2; graph.edges[4].dest = 3; graph.edges[4].weight = 4; graph.KruskalMST(); } } ``` 希望能对你有所帮助!接下来,请问你想问我什么问题?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值