当前位置:网站首页>Minimum spanning tree: Kruskal
Minimum spanning tree: Kruskal
2022-07-23 21:01:00 【*Ruthless*】
List of articles
Kruskal
The algorithm of adding edges one by one to generate the minimum spanning tree
Use Kruskal Concurrent search set is used
Initialize and query set , At the beginning, the representative yuan of all points is itself , Each point itself constitutes a set ;
Sort the edge weights from small to large ;
Enumerate all edges in the order of the edge weight from small to large , If the two vertices connected by the current edge are in the same set ( Their representative elements are the same ), Then do nothing , otherwise
Add this edge to the edge set of the minimum spanning tree ;
Merge the set where the two points connected by this edge are located with the merge operation of the joint search set ;
Until only one set is left .
Time complexity : O ( m l o g n ) O(mlogn) O(mlogn)
struct Node
{
int x, y, v;
bool operator<(const Node &A) const
{
return v < A.v;
}
} a[M];
int n, m, fa[N];
int findest(int i)
{
if (i == fa[i])
return i;
return fa[i] = findest(fa[i]);
}
int Kruskal()
{
for (int i = 1; i <= n; i++)
fa[i] = i;
sort(a + 1, a + m + 1);
int ans = 0, cnt = n;
for (int i = 1; i <= m; i++)
{
int x = findest(a[i].x), y = findest(a[i].y);
if (x != y)
{
fa[x] = y;
ans += a[i].v;
--cnt;
}
if (cnt == 1)
break;
}
if (cnt != 1)
return -1;
else
return ans;
}
边栏推荐
- 《迷失》stray工人帽子获得方法 工人安全帽在哪里?
- 深入浅出边缘云 | 1. 概述
- 1063 Set Similarity
- Interpretation of Flink catalog
- Connect with Hunan Ca and use U_ Key login
- 当我们在谈论陈春花和华为时,我们到底在讨论什么?
- 最小生成树:Kruskal
- From which dimensions can we judge the quality of code? How to have the ability to write high-quality code?
- 实现生成订单30分钟未支付,则自动取消
- VRRP+MSTP配置详解【华为eNSP实验】
猜你喜欢
随机推荐
Green-Tao 定理的证明 (2): Von Neumann 定理的推广
[Yunxiang book club No. 13] Chapter IV packaging format and coding format of audio files
VLAN综合实验
An interview question about common pitfalls in golang for range
Cesium knockout怎么用?
2022.7.11mySQL作业
Unity解决动画不可用:The AnimationClip ‘XXX‘ used by the Animation component ‘XXX‘ must be marked as Legacy.
信号的理解
利用ENVI对TROPOMI(哨兵5P)数据预处理
How to introduce your project experience in the interview
模块化开发
对接湖南CA使用U_KEY登录
OpenLayers实例-Accessible Map-可访问的地图
Improving Performance with Explicit Rendering(通过显式渲染提高性能)
Connect with Hunan Ca and use U_ Key login
支付宝常用接口统一封装,可直接支付参数使用(适用于H5、PC、APP)
Tropomi (sentinel 5p) data introduction and download method
第三届SLAM技术论坛-吴毅红教授
Proof of green Tao theorem (2): generalization of von Neumann theorem
当我们在谈论陈春花和华为时,我们到底在讨论什么?








