当前位置:网站首页>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;
}
边栏推荐
- Installation and testing of pyflink
- go-zero微服务实战系列(九、极致优化秒杀性能)
- Docker method to install MySQL
- Google released a security update to fix 0 days that have been used in chrome
- Add the applet "lazycodeloading": "requiredcomponents" in taro,
- C语言实例_3
- Neon Optimization: an optimization case of log10 function
- Yunna | work order management software, work order management software app
- 数据手册中的词汇
- 2022 Google CTF SEGFAULT LABYRINTH wp
猜你喜欢
随机推荐
Supersocket 1.6 creates a simple socket server with message length in the header
Receive user input, height BMI, BMI detection small business entry case
C language instance_ five
Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
一起看看matlab工具箱内部是如何实现BP神经网络的
Dark horse notes - create immutable sets and streams
自旋与sleep的区别
Install Firefox browser on raspberry pie /arm device
Amway wave C2 tools
交叉验证如何防止过拟合
机器学习:随机梯度下降(SGD)与梯度下降(GD)的区别与代码实现。
黑马笔记---创建不可变集合与Stream流
2022 Google CTF SEGFAULT LABYRINTH wp
Clickhouse fields are grouped and aggregated, and SQL is queried according to the granularity of any time period
从零开始匹配vim(0)——vimscript 简介
Neon Optimization: summary of performance optimization experience
Gnet: notes on the use of a lightweight and high-performance go network framework
The MySQL database in Alibaba cloud was attacked, and finally the data was found
C # method of calculating lunar calendar date 2022
数据手册中的词汇









