P3366 最小生成树

版权声明:转载请注明原文地址即可,要是本文对您有些许帮助的话,请您在下方点个赞,谢谢啦ヾ(o◕∀◕)ノヾ https://blog.csdn.net/qq_33583069/article/details/88591390
#include<bits/stdc++.h>
using namespace std;
#define N 5010
#define M 200010
struct edge{
	int from,to,w;
	bool operator < (const edge tmp)const{
		return this->w<tmp.w;
	}
}e[M];
int n,m,fa[N];
int find(int u){
	return u==fa[u]?u:fa[u]=find(fa[u]);
}
void kruskal(){
	sort(e,e+m);
	int fx,fy,cnt = 0,ans = 0;
	for(int i=1;i<=m;i++){
		fx = find(e[i].from);
		fy = find(e[i].to);
		if(fx!=fy){
			fa[fx]=fy;
			ans+=e[i].w;	
			if(++cnt==n-1)break; 
		}		
	}
	if(cnt<n-1)cout<<"orz";
	else cout<<ans;
}
int main(){
	ios::sync_with_stdio(false);
	cin>>n>>m;
	for(int i=1;i<=n;i++)fa[i]=i;
	for(int i=1;i<=m;i++)
		cin>>e[i].from>>e[i].to>>e[i].w;
	kruskal();
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_33583069/article/details/88591390