算法与数据结构实验题 7.4 玩游戏的亚索 (最小支撑树)

1、题目:


2、代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
struct edge
{
	int u;
	int v;
	int w;
} e[500005];
int father[10005];
bool cmp1(edge e1,edge e2)
{
	return e1.w<e2.w;
}

int UFfind(int x)
{
	if(x!=father[x])
	{
		father[x]=UFfind(father[x]);
	}
	return father[x];
}

int main()
{
	int n,m;
	int ans=0,count=0;
	scanf("%d%d",&n,&m);
	int i;
	for(i=0; i<n; i++)
	{
		father[i]=i;
	}
	for(i=0; i<m; i++)
	{
		scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
	}
	sort(e,e+m,cmp1);

	for(i=0; i<m; i++)
	{
		int fa=UFfind(e[i].u);
		int fb=UFfind(e[i].v);
		if(fa!=fb)
		{
			father[fa]=fb;
			ans+=e[i].w;
			count++;
		}
		if(count==n-1)
		{
			break;
		}
	}
	printf("%d\n",ans);
	return 0;
}
posted @ 2016-12-01 15:15  laixl  阅读(271)  评论(0编辑  收藏  举报