「CH6201」走廊泼水节

传送门

考虑 \(\text{Kruskal}\) 的过程以及用到一个最小生成树的性质即可。

在联通两个联通块时,我们肯定会选择最小的一条边来连接这两个联通块,那么这两个联通块之间的其他边都必须比这条边长,不然最小生成树就不唯一。

又为了让答案最小化,我们就只需要让这些其他边比当前边多 \(1\) 就好了。

参考代码:

#include <algorithm>
#include <cstdio>
#define rg register
#define file(x) freopen(x".in", "r", stdin), freopen(x".out", "w", stdout)
using namespace std;
template < class T > inline void read(T& s) {
s = 0; int f = 0; char c = getchar();
while ('0' > c || c > '9') f |= c == '-', c = getchar();
while ('0' <= c && c <= '9') s = s * 10 + c - 48, c = getchar();
s = f ? -s : s;
} const int _ = 6010;
typedef long long LL; int n, Fa[_], siz[_];
struct node { int x, y, z; } t[_];
inline bool cmp(const node& a, const node& b) { return a.z < b.z; } inline int Find(int x) { return Fa[x] == x ? x : Fa[x] = Find(Fa[x]); } inline void solve() {
read(n);
for (rg int i = 1; i <= n; ++i) Fa[i] = i, siz[i] = 1;
for (rg int x, y, z, i = 1; i < n; ++i)
read(x), read(y), read(z), t[i] = (node) { x, y, z };
sort(t + 1, t + n, cmp);
LL ans = 0;
for (rg int i = 1; i < n; ++i) {
int x = Find(t[i].x), y = Find(t[i].y);
if (x == y) continue;
ans += 1ll * (t[i].z + 1) * (siz[x] * siz[y] - 1);
Fa[x] = y, siz[y] += siz[x];
}
printf("%lld\n", ans);
} int main() {
#ifndef ONLINE_JUDGE
file("cpp");
#endif
int T; read(T);
while (T--) solve();
return 0;
}

最新文章

  1. Mysql 查看、创建、更改 数据库和表
  2. Ubuntu16.04LTS国内快速源
  3. 使用mailx发送邮件
  4. the bundle at bundle path is not signed using an apple submission certificate
  5. Sharepoint学习笔记—习题系列--70-576习题解析 -(Q32-Q35)
  6. POJ 2785 4 Values whose Sum is 0
  7. 记录一下跟Python有关的几个拓展名
  8. WEB安全入门
  9. class path resource [config.xml] cannot be opened because it does not exist
  10. 【转】Steam 开发者收入计算
  11. C# Entity To Json
  12. kafka原理和架构
  13. 写SQL语句常见的问题
  14. idea配置.gitignore后无法起作用
  15. [python] os.path.join() 与 sys.path
  16. Linux安装Tomcat-Nginx-FastDFS-Redis-Solr-集群——【第九集之安装Tomcat+Nginx反向代理Tomcat集群】
  17. 涂抹mysql笔记-mysql性能调优和诊断
  18. linux中的IP地址的修改
  19. 数值分析 最小二乘 matlab
  20. aps.net MVC view 判断方法

热门文章

  1. java web编写四则运算
  2. 【代码学习】PYTHON 闭包
  3. 入门chrome插件开发教程和经验总结,一篇就搞掂!
  4. MyBatis XML常用配置
  5. watch监听变化
  6. SDNU_ACM_ICPC_2020_Winter_Practice_1st
  7. 基于springboot实现轮询线程自动执行任务
  8. Python web在IIS上发布方法和原理
  9. 兵贵神速!掌握这10个Python技巧,让你代码工作如鱼得水
  10. SmartAssembly批处理用法