当前位置:网站首页>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;
}
边栏推荐
- 子网划分、构造超网 典型题
- Taro 小程序开启wxml代码压缩
- POJ 3177 Redundant Paths POJ 3352 Road Construction(双连接)
- docker 方法安装mysql
- Oracle: Practice of CDB restricting PDB resources
- C language instance_ five
- golang 基础 —— 数据类型
- Asset security issues or constraints on the development of the encryption industry, risk control + compliance has become the key to breaking the platform
- 从底层结构开始学习FPGA----FIFO IP的定制与测试
- Make Jar, Not War
猜你喜欢
Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
Installation of gazebo & connection with ROS
Transplant DAC chip mcp4725 to nuc980
LeetCode:1175. Prime permutation
对C语言数组的再认识
tansig和logsig的差异,为什么BP喜欢用tansig
Clickhouse fields are grouped and aggregated, and SQL is queried according to the granularity of any time period
Make Jar, Not War
AI automatically generates annotation documents from code
免费白嫖的图床对比
随机推荐
AI automatically generates annotation documents from code
黑马笔记---异常处理
Make Jar, Not War
数据手册中的词汇
736. Lisp 语法解析 : DFS 模拟题
Oracle: Practice of CDB restricting PDB resources
C language instance_ three
[advanced C language] 8 written questions of pointer
shell脚本快速统计项目代码行数
Implementation principle of waitgroup in golang
C语言实例_3
云呐|工单管理办法,如何开展工单管理
域分析工具BloodHound的使用说明
Taro 小程序开启wxml代码压缩
Realize incremental data synchronization between MySQL and ES
What does security capability mean? What are the protection capabilities of different levels of ISO?
[chip scheme design] pulse oximeter
c语言—数组
让我们,从头到尾,通透网络I/O模型
Docker method to install MySQL