最小生成树模板题题解 c++

本文介绍了如何使用克鲁斯卡尔算法解决最小生成树问题,提供了C++代码实现,并提到了在快写时可能出现的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请先掌握一些最小生成树的知识
题目传送门
用克鲁斯卡尔算法,通过并查集合并两个节点和选择是否加边。
代码 Lang:c++

#include<bits/stdc++.h>
using namespace std;
#define RI register int
inline int read()
{
	int s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){s=s*10+ch-'0';ch=getchar();}
	return s*w;
}
int n,m;
const int maxm=200010;
struct edge{
	int u,v,w;
}e[maxm];
bool cmp(edge x,edge y)
{
	return x.w<y.w;
}
int fa[5010];
int findd(int x)
{
	if(x!=fa[x])return findd(fa[x]);
	return x;
}
int ans;
void KKK()
{
	int cnt=0;
	sort(e+1,e+m+1,&cmp);
	for(RI i=1;i<=m;i++)
	{
		int x=findd(e[i].u),y=findd(e[i].v);
		if(x==y)continue;
		fa[x]=y;cnt++;
		ans+=e[i].w;
		if(cnt==n-1)return;
	}
	printf("orz");
	exit (0);
}
int out(int x)
{
	if(x>9)out(x/10);
	putchar(x%10+'0');
}
int main()
{
	n=read();m=read();
	for(RI i=1;i<=n;i++)
	 fa[i]=i;
	for(RI i=1;i<=m;i++)
	{
		e[i].u=read();
		e[i].v=read();
		e[i].w=read(); 
	}
	KKK();
	printf("%d",ans);
	return 0;
 } 

KKK 指克鲁斯卡尔算法表明了我对 KKK 的崇拜
使用快写会RE三个点,我也不知道为什么
谢谢阅读

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值