当前位置:网站首页>最小生成树:Kruskal
最小生成树:Kruskal
2022-07-23 20:31:00 【*﹏ℳ๓无情*】
文章目录
Kruskal
一条条添加边生成最小生成树的算法
使用Kruskal使用了并查集
初始化并查集,一开始所有的点的代表元都是它自己,每个点本身构成一个集合;
将边权从小到大的顺序排序;
按边权从小到大的顺序依次枚举所有的边,如果当前这条边连接的两个顶点位于同一集合(它们的代表元是一样的),则什么都不做,否则
将这条边添加到最小生成树的边集里;
用并查集的合并操作将这条边连接的两个点所在的集合合并;
直到只剩下一个集合结束。
时间复杂度: 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;
}
边栏推荐
- 不用MQTT C库就能实现MQTT连接、订阅和发布
- Cesium 事件详解(鼠标事件、相机事件、键盘事件、场景触发事件)
- 做一个有职业操守的软件匠人
- 实现生成订单30分钟未支付,则自动取消
- 很漂亮的马路
- NLP领域历史最全必读经典论文分类整理分享(附中文解析)
- OpenLayers实例-Animated GIF-GIF动画
- MySQL(3)
- 【Kernel】驱动开发学习之Platform平台总线模型
- Choice is greater than effort! Guiyang campus Xiaoge 0 foundation successfully transferred to software testing and gained 12K!
猜你喜欢

138-查询案例-涉及知识点:forEach遍历&computed计算属性&v-for循环

The instructions on Microsoft website about opening or closing smartscreen in edge browser are incorrect

高数下|三重积分的计算2|高数叔|手写笔记

深度学习-NLP经典论文、课程、论文等资源整理分享

【Kernel】驱动开发学习之Platform平台总线模型

【pdd面试】分析手机中的应用(相机)的活跃情况

今日睡眠质量记录81分

《迷失》stray工人帽子获得方法 工人安全帽在哪里?

Understanding of signals

信号的理解
随机推荐
Cesium 事件详解(鼠标事件、相机事件、键盘事件、场景触发事件)
138-查询案例-涉及知识点:forEach遍历&computed计算属性&v-for循环
Understanding of signals
[cloud co creation] what magical features have you encountered when writing SQL every day?
解决1秒钟内,用户快速点击,重复请求的问题
从ACL 2022 Onsite经历看NLP热点
shell脚本中$#、$*、[email protected]、$?、$0等含义一文搞懂
2022.7.11 MySQL job
Vrrp+mstp configuration details [Huawei ENSP experiment]
MySQL(3)
A beautiful road
Major upgrade of openim - group chat reading diffusion model release group management function upgrade
深度学习-NLP经典论文、课程、论文等资源整理分享
Day 11: continue the basic configuration of BGP for day 10
Microservice architecture vs single service architecture [what can Huawei cloud service do in the microservice mode]
AB team score flow chart, get the names of the players who score three consecutive times and the names of the players who catch up with and surpass the opponents each time (PDD)
【力扣】三数之和
Cesium 获取经纬度的几种方法
jsp+ssm+mysql实现的租车车辆管理系统汽车租赁
[Yunxiang book club No. 13] Chapter IV packaging format and coding format of audio files