53. 寻宝(第七期模拟笔试)(最小生成树练习)


53. 寻宝(第七期模拟笔试)(最小生成树练习)

原创 于 2023-10-28 16:40:01 发布 · 粉丝可见 · 186 阅读 · 0 · 0 · 本内容遵循CC 4.0 BY-SA版权协议 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/134092851

本题链接: 卡码网KamaCoder

题目:

样例:

cobol<br/>7 11<br/>1 2 1<br/>1 3 1<br/>1 5 2<br/>2 6 1<br/>2 4 2<br/>2 3 2<br/>3 4 1<br/>4 5 1<br/>5 6 2<br/>5 7 1<br/>6 7 1<br/>
6

思路:

由题意,这里是需要遍历完全部的顶点,求遍历完全部点的花费最短距离。

从题干 ‘每个顶点都要访问一遍’, 我们就应该联想到最小生成树,最小生成树中,有朴素版Prim最小生成树算法,和并查集的优化版Kruskal算法,由于这里的数据范围较大,所以我们应该使用并查集的优化版Kruskal算法。

代码详解如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define endl '\n'
#define YES puts("YES")
#define NO puts("NO")
#define umap unordered_map
#define All(x) x.begin(),x.end()
#pragma GCC optimize(3,"Ofast","inline")
#define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10;

int n,m,ans;

// 定义结点之间和边权的关系结构体,并定义数组
struct Edge
{
int a,b,w;
// 定义排序规则,将边权最小的放在前面
inline bool operator<(const Edge&t)const
{
return w < t.w;
}
}edge[N];

umap<int,int>p; // 标记的结点集合

// 集合查找根节点函数
inline int Find(int &x)
{
int t = x;
while(x != p[x]) x = p[x];
p[t] = x; // 剪枝路径操作
return x;
}

inline void Kruskal()
{
// 排序好最小边权,我们优先连接最小边权的结点
sort(edge,edge + m);

// 初始化各个结点的连接根节点为本身
for(int i = 0;i <= n;++i) p[i] = i;

// 遍历每一条边权关系
for(int i = 0;i < m;++i)
{
// 获取存储关系的两个结点
int a = edge[i].a;
int b = edge[i].b;
// 查找对应结点的根节点
a = Find(a),b = Find(b);
if(a != b)
{
// 如果这两个结点未连接,我们将它们连接起来
p[a] = b;
ans += edge[i].w; // 累加最小边权
}
}
return ;
}

inline void solve()
{
// 输入各个信息
cin >> n >> m;
for(int i = 0;i < m;++i)
{
int a,b,w;
cin >> a >> b >> w;
// 存储记录好结点的边权关系
edge[i] = {a,b,w};
}

// 开始克鲁斯卡尔算法
Kruskal();

// 输出答案
cout << ans << endl;
}

int main()
{
// freopen("a.txt", "r", stdin);
IOS;
int _t = 1;
// cin >> _t;
while (_t--)
{
solve();
}

return 0;
}

最后提交:


觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭

微信二维码

wechat pay

支付宝二维码

ali pay

53. 寻宝(第七期模拟笔试)(最小生成树练习)
http://blog.angindem.cn/2023/10/28/Angindem-CSDN博客/101_101/
作者
Angindem
发布于
2023年10月28日
许可协议