当前位置:网站首页>AcWing 346. 走廊泼水节 题解(推公式、最小生成树)
AcWing 346. 走廊泼水节 题解(推公式、最小生成树)
2022-07-06 18:00:00 【乔大先生】
AcWing 346. 走廊泼水节
解题关键在于推出公式:**(Size[a] * Size[b] - 1) * (w + 1)**这个公式的意义按揭的:遍历到某条边连接的属于两个不同的连通块的两个点,将两个联通块的所有点互相连接,减去已经存在的一条边 ,推出公式后,按照最小生成树的算法遍历所有边,找出不在一个连通块的两个点用公式累加计算值
#include<bits/stdc++.h>
using namespace std;
const int N = 6010;
struct Edge{
int a, b, w;
bool operator< (const Edge &t) const {
return w < t.w;
}
}e[N * 4];
int T, n, m;
int p[N];
int Size[N];
int find(int x){
if(x != p[x]) p[x] = find(p[x]);
return p[x];
}
int main()
{
cin>>T;
while(T -- ){
cin>>n;
int res = 0;
for(int i = 0; i < n - 1; i ++ ){
int a, b, w;
cin>>a>>b>>w;
e[i] = {
a, b, w};
}
//初始化并查集数组
for(int i = 1; i <= n; i ++ ){
p[i] = i;
Size[i] = 1;
}
sort(e, e + n - 1);
for(int i = 0; i < n - 1; i ++ ){
int a = find(e[i].a), b = find(e[i].b), w = e[i].w;
if(a != b){
res += (Size[a] * Size[b] - 1) * (w + 1); //公式,将两个联通块的所有点互相连接,减去已经存在的一条边
p[a] = b;
Size[b] += Size[a];
}
}
cout<<res<<endl;
}
return 0;
}
边栏推荐
- The difference between spin and sleep
- swiper组件中使用video导致全屏错位
- 从零开始匹配vim(0)——vimscript 简介
- table表格设置圆角
- Wood extraction in Halcon
- Implementation principle of waitgroup in golang
- [signal and system]
- Neon Optimization: summary of performance optimization experience
- 一起看看matlab工具箱内部是如何实现BP神经网络的
- [case sharing] basic function configuration of network loop detection
猜你喜欢

Asset security issues or constraints on the development of the encryption industry, risk control + compliance has become the key to breaking the platform

golang中的Mutex原理解析

Let's see through the network i/o model from beginning to end

域分析工具BloodHound的使用说明

2022 Google CTF SEGFAULT LABYRINTH wp

让我们,从头到尾,通透网络I/O模型

对C语言数组的再认识

修改px4飞控的系统时间

Js逆向——捅了【马蜂窝】的ob混淆与加速乐

Yunna | work order management software, work order management software app
随机推荐
修改px4飞控的系统时间
Yunna - work order management system and process, work order management specification
Share a general compilation method of so dynamic library
[JS] obtain the N days before and after the current time or the n months before and after the current time (hour, minute, second, year, month, day)
[100 cases of JVM tuning practice] 05 - Method area tuning practice (Part 2)
分享一个通用的so动态库的编译方法
405 method not allowed appears when the third party jumps to the website
The MySQL database in Alibaba cloud was attacked, and finally the data was found
1123. 最深叶节点的最近公共祖先
736. LISP syntax parsing: DFS simulation questions
7.6模拟赛总结
go-zero微服务实战系列(九、极致优化秒杀性能)
剑指 Offer II 035. 最小时间差-快速排序加数据转换
Gnet: notes on the use of a lightweight and high-performance go network framework
Spark TPCDS Data Gen
子网划分、构造超网 典型题
Taro 小程序开启wxml代码压缩
C# 计算农历日期方法 2022
NEON优化:性能优化常见问题QA
如何管理分布式团队?