图论-最小生成树-kruskal算法-洛谷P3366

图论-最小生成树-kruskal算法-洛谷P3366_第1张图片

#include
using namespace std;

int N,M;

int s[1000005] = {};

int find_set(int u) 
{
	int r = u;
	while(r != s[r]) r = s[r]; 
 
	int i = u,j;
	while(i != r)
	{
		j = s[i]; 
		s[i] = r;
		i = j; 
	}
	return r;
} 


struct node
{
	int x,y,z;
}edge[1000005];

bool cmp(node tmp1,node tmp2)
{
	return tmp1.z < tmp2.z;
}

int kruskal()
{
	int cnt = 0,x1,y1;
	for(int i=1;i <= N;i++) s[i] = i;
	sort(edge + 1,edge + 1 + M,cmp);
	for(int i=1;i <= M;i++)
	{
		x1 = find_set(edge[i].x);
		y1 = find_set(edge[i].y);
		if(x1 == y1) continue;
		s[x1] = y1;
		cnt += edge[i].z;
	}
	return cnt;
}

int main()
{
	scanf("%d%d",&N,&M);
	for(int j=1;j <= M;j++)
	{
		scanf("%d%d%d",&edge[j].x,&edge[j].y,&edge[j].z);
	}
	int judge=0,ans=0;
	ans = kruskal();
	for(int j=1;j <= N;j++)
	{
		if(s[j] == j) judge++;
	}
	if(judge == 1)	printf("%d",ans);
	else printf("orz");
	return 0;
}

 

你可能感兴趣的:(c++,算法)