当前位置:网站首页>AcWing 346. Solution to the problem of water splashing festival in the corridor (deduction formula, minimum spanning tree)
AcWing 346. Solution to the problem of water splashing festival in the corridor (deduction formula, minimum spanning tree)
2022-07-07 01:36:00 【Mr. Qiao Da】
AcWing 346. Corridor Water Splashing Festival
The key to solving the problem is to deduce the formula :**(Size[a] * Size[b] - 1) * (w + 1)** The meaning of this formula is mortgage : Traverse to two points belonging to two different connected blocks connected by a certain edge , Connect all points of the two connecting blocks to each other , Subtract an existing edge , After introducing the formula , Traverse all edges according to the algorithm of minimum spanning tree , Find out two points that are not in a connected block and accumulate the calculated value with a formula
#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};
}
// Initialize and query array
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); // The formula , Connect all points of the two connecting blocks to each other , Subtract an existing edge
p[a] = b;
Size[b] += Size[a];
}
}
cout<<res<<endl;
}
return 0;
}
边栏推荐
猜你喜欢
![[signal and system]](/img/aa/a65d6da1d1d9410254ca7b775e24a6.png)
[signal and system]

LeetCode:1175. 质数排列

According to the analysis of the Internet industry in 2022, how to choose a suitable position?

今日问题-2022/7/4 lambda体中修改String引用类型变量

Gazebo的安装&与ROS的连接

2022 Google CTF SEGFAULT LABYRINTH wp

如何管理分布式团队?

对C语言数组的再认识

1123. The nearest common ancestor of the deepest leaf node

405 method not allowed appears when the third party jumps to the website
随机推荐
从底层结构开始学习FPGA----FIFO IP的定制与测试
Installation and testing of pyflink
docker 方法安装mysql
C language - array
Vocabulary in Data Book
C语言实例_4
swiper组件中使用video导致全屏错位
黑马笔记---异常处理
table表格设置圆角
字节P7专业级讲解:接口测试常用工具及测试方法,福利文
736. LISP syntax parsing: DFS simulation questions
Using the entry level of DVA in taro3.*
Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which
长按按钮执行函数
一起看看matlab工具箱内部是如何实现BP神经网络的
Comparison of picture beds of free white whoring
AI automatically generates annotation documents from code
Case development of landlord fighting game
Add the applet "lazycodeloading": "requiredcomponents" in taro,
hdu 4661 Message Passing(木DP&amp;组合数学)