P3366 【模板】最小生成树【并查集】

题目描述

如题,给出一个无向图,求出最小生成树,如果该图不连通,则输出 orz

输入格式

第一行包含两个整数 N,M,表示该图共有 N 个结点和 M 条无向边。

接下来 M 行每行包含三个整数 Xi​,Yi​,Zi​,表示有一条长度为 Zi​ 的无向边连接结点 Xi​,Yi​。

输出格式

如果该图连通,则输出一个整数表示最小生成树的各边的长度之和。如果该图不连通则输出 orz

输入输出样例

输入 #1

4 5
1 2 2
1 3 2
1 4 3
2 3 4
3 4 3

 输出 #1

7

说明/提示

数据规模:

对于 20% 的数据,N≤5,M≤20。

对于 40% 的数据,N≤50,M≤2500。

对于 70% 的数据,N≤500,M≤10^4。

对于 100\%100% 的数据:1≤N≤5000,1≤M≤2×10^5,1≤Zi​≤10^4。

AC代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
struct node{
	int from;
	int to;
	int data;
}tree[200005];
int vis[200005];

int father(int x){
	if(x==vis[x]){
		return x;
	}
	return vis[x]=father(vis[x]);
}
void link(int x,int y){
	int hx=father(x);
	int hy=father(y);
	vis[hx]=hy;
}
bool cmp(node a,node b){
	return a.data<b.data;
}
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		vis[i]=i;
	}
	for(int i=0;i<m;i++){
		int a,b,c;
		scanf("%d%d%d",&a,&b,&c);
		tree[i].from=a;
		tree[i].to=b;
		tree[i].data=c;
	}
	sort(tree,tree+m,cmp);
	int num=0;
	int sum=0;
	for(int i=0;i<m;i++){
		//cout<<tree[i].from<<endl;
		//cout<<father(tree[i].from)<<' '<<father(tree[i].to)<<endl;
		if(father(tree[i].from)!=father(tree[i].to)){
			link(tree[i].from,tree[i].to);
			num+=tree[i].data;
			sum++;
			if(sum==n-1) break;
		}
		//cout<<num<<endl;
	}
	if(sum!=n-1){
		printf("orz\n");
		return 0;
	}
	printf("%d\n",num);
	return 0;
}
//576

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瘾ิۣۖิۣۖิۣۖิꦿ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值