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

本题链接:卡码网KamaCoder

题目:

样例:

输入
7 11
1 2 1
1 3 1
1 5 2
2 6 1
2 4 2
2 3 2
3 4 1
4 5 1
5 6 2
5 7 1
6 7 1
输出
6

思路:

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

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

代码详解如下:

#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;
}

最后提交:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值