\(Kruskal\) 算法

Luogu P3366 为例题

实现方法:从小到大遍历每一条线,如果该线连接的两点已经都在树内则不处理,否则描出这条线

从小到大是一个贪心的实现方法,由于每描出一条线,就会生成一棵新的树或将一个点加入一棵树中。第一个点不需要连线处理,因此描出这棵树所需要的边的数量一定是这棵树的点的数量减一(也许树本身就存在这样的性质?)

当然,有一个例外,那就是给出的图不连通

我们暂时不用考虑图的连通性的问题,因为例题给出的要求是:对于所有不连通的图,输出 orz

使用并查集维护该树

示例代码:

#include <bits/stdc++.h>

using namespace std;

const int N = 2e5 + 5;

pair<int, pair<int, int>> g[N];  // The weight on the line between Point A and Point B, Point A, Point B

int fa[N];  // Father Point

int f(int x) {  // Finding Point X's Extra Grandpa
if (fa[x] == x) return x;
return fa[x] = f(fa[x]); // Disjoint Set Union path compression
} int main() {
int m, n;
cin >> n >> m;
for (int i = 1, u, v, w; i <= m; i++) // Saving
cin >> u >> v >> w,
g[i].first = w,
g[i].second.first = u,
g[i].second.second = v;
for (int i = 1; i <= n; i++) fa[i] = i; // Initialize All Points' Father as themselves
sort(g + 1, g + m + 1);
int ans = 0, cnt = 0; // Use cnt to make sure that all point was connected
for (int i = 1; i <= m; i++) {
int u = g[i].second.first, v = g[i].second.second, w = g[i].first; // Reading
if (f(u) == f(v)) continue; // Had been connected
ans += w, fa[f(v)] = fa[u], cnt++; // Add the weight, connect Point V and Point U
}
if (cnt == n - 1) cout << ans << endl; // If there's n points, then there will be connecting for n - 1 times
else cout << "orz" << endl; // Some points didn't connected
return 0;
}

随机推荐

  1. vue3.4中defineModel中默认值是复杂数据类型 (注意!!!)

    const drillFields = defineModel<string[]>('drillFields', { get(val) { return reactive(val || [ ...

  2. 前端 PM 分享:PM 需要做的事情

    个人经验分享 PM PM( Project Manager ) PM( Product Manager ) 一.什么情况下需要前端担任 PM? 在我之前遇到的项目中,大多数项目的 PM 是由后端/产品 ...

  3. 在 JS 中使用 canvas 给图片添加文字水印

    实现说明: 1.先通过 new Image() 载入图片: 2.图片加载成功后使用 drawImage() 将图片绘制到画布上: 3.最后使用 fillText() 函数绘制水印. 下面展示了详细用法 ...

  4. java学习之旅(day.06)

    switch多选择结构 多选择结构还有一个实现方式就是switch case switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支 switch(expression ...

  5. 记一次 .NET某企业数字化平台 崩溃分析

    一:背景 1. 讲故事 前些天群里有一个朋友说他们软件会偶发崩溃,想分析看看是怎么回事,所幸的是自己会抓dump文件,有了dump就比较好分析了,接下来我们开始吧. 二:WinDbg 分析 1. 程序 ...

  6. swift_slowAlloc Crash 分析

    一.Crash详情 Crash类型 exception EXC_BREAKPOINT (SIGTRAP) reason EXC_BREAKPOINT EXC_ARM_BREAKPOINT fault_ ...

  7. kettle从入门到精通 第三十五课 kettle 变量

    1.设置变量 a.可以通过转换中的"设置变量"步骤进行设置. b.手动通过kettle.properties文件或通过"编辑"菜单中的"设置环境变量& ...

  8. .net core .net6 webapi 连接mysql 8

    1.表结构: CREATE TABLE `table2` ( `id` BIGINT NOT NULL AUTO_INCREMENT, `myname` varchar(255) NOT NULL, ...

  9. 字符数组数据映射转换到实体对象model注解方式 demo

    1.model对象 public class UserModel { @ColumnAnnotation(index=0) private String username; @ColumnAnnota ...

  10. Java接口签名和验签

    Java接口签名和验签 import com.alibaba.fastjson.JSON; import org.apache.commons.lang3.StringUtils; import ja ...