当前位置:网站首页>AcWing 1141. 局域网 题解(kruskalkruskal 求最小生成树)
AcWing 1141. 局域网 题解(kruskalkruskal 求最小生成树)
2022-07-06 18:00:00 【乔大先生】
AcWing 1141. 局域网
克鲁斯卡尔求最小生成森林(就是每个联通块求最小生成树),克鲁斯卡尔的算法过程刚好是从小到大依次将边加入集合中,所以这里刚好利用克鲁斯卡尔算法求
#include<bits/stdc++.h>
using namespace std;
const int N = 210;
int p[N]; //并查集祖先数组
int n, m;
int res; //记录答案
struct Edge{
int a, b, w;
bool operator<(const Edge &t) const {
return w < t.w;
}
}edge[N];
int find(int x){
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main()
{
cin>>n>>m;
for(int i = 1; i <= n; i ++ ) p[i] = i; //注意初始化并查集
for(int i = 0; i < m; i ++ ){
int a, b, c;
cin>>a>>b>>c;
edge[i] = {
a, b, c};
}
sort(edge, edge + m);
for(int i = 0; i < m; i ++ ){
//a和b相连才会被遍历到,所以这里不用担心将两个不同的连通块连在一起
int a = find(p[edge[i].a]), b = find(p[edge[i].b]);
if(a != b) p[a] = b; //如果不在一个集合内,就加入到一个集合内
else res += edge[i].w; //如果这两个点在一个联通块内,说明他们已经通过花费更小的边连在一起,目前这个边就可以删除了
}
cout<<res<<endl;
return 0;
}
边栏推荐
- go-zero微服务实战系列(九、极致优化秒杀性能)
- 1123. The nearest common ancestor of the deepest leaf node
- JTAG principle of arm bare board debugging
- Transplant DAC chip mcp4725 to nuc980
- Wood extraction in Halcon
- taro3.*中使用 dva 入门级别的哦
- Dark horse notes - exception handling
- Oracle: Practice of CDB restricting PDB resources
- Google released a security update to fix 0 days that have been used in chrome
- NEON优化:性能优化常见问题QA
猜你喜欢
Yunna | work order management measures, how to carry out work order management
黑马笔记---异常处理
HMM 笔记
第三方跳转网站 出现 405 Method Not Allowed
Instructions for using the domain analysis tool bloodhound
云呐-工单管理制度及流程,工单管理规范
c语言—数组
Typical problems of subnet division and super network construction
黑马笔记---创建不可变集合与Stream流
tansig和logsig的差异,为什么BP喜欢用tansig
随机推荐
Yunna | work order management software, work order management software app
C language instance_ two
golang 基础 —— 数据类型
C language - array
ClickHouse字段分组聚合、按照任意时间段粒度查询SQL
POJ 3177 Redundant Paths POJ 3352 Road Construction(双连接)
NEON优化:性能优化常见问题QA
[signal and system]
WCF基金会
移植DAC芯片MCP4725驱动到NUC980
table表格设置圆角
【信号与系统】
Neon Optimization: summary of performance optimization experience
搭建【Redis in CentOS7.x】
Neon Optimization: an instruction optimization case of matrix transpose
What are the differences between Oracle Linux and CentOS?
Make Jar, Not War
云呐|工单管理软件,工单管理软件APP
C语言实例_5
Byte P7 professional level explanation: common tools and test methods for interface testing, Freeman