ccf csp-201812-4-数据中心(最小生成树+并查集)

原试题点击此处

代码如下

#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100005;
int n;
struct EDGE{
	int u,v,w;
}edge[N];
int Arry[N];
int cmp(EDGE a,EDGE b){
	return a.w<b.w;
}
void init(){
	for(int i = 0; i < n; i++){
		Arry[i] = i;
	}
}
int Find(int num){
	int root = num,tmp;
	while(Arry[root]!=root){
		root = Arry[root];
	}
	while(num != root){
		tmp = Arry[num];
		Arry[num] = root;
		num = tmp;
	}
	return num;
}
bool Union(int a,int b){
	int aRoot = Find(a);
	int bRoot = Find(b);
	if(aRoot != bRoot){
		Arry[aRoot] = bRoot;
		return true;
	}
	return false;
}
int main()
{
	int m,root,u,v,w,ans = 0,num = 0;
	scanf("%d%d%d", &n, &m, &root);
	for(int i = 0; i < m; i++){
		scanf("%d%d%d", &edge[i].u,&edge[i].v,&edge[i].w);
	}
	sort(edge, edge+m, cmp);
	init();
	for(int i = 0; i < m; i++){
		if(Union(edge[i].u,edge[i].v)){
			ans = edge[i].w;
			if(++num == n-1) break;
		}
	}
	printf("%d\n", ans);
	return 0;
}
发布了110 篇原创文章 · 获赞 746 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_42437577/article/details/104279730