p112 还是畅通工程

#include <stdio.h>//最小生成树,将输入的所有边排序,从小到大遍历,当且仅当两个点之间没有通路时,合并所有结点,并把权值加上ans
#include <algorithm>

using namespace std;

#define N 101
int Tree[N];

struct edge{
	int a,b;
	int cost;
	bool operator < (const edge& A) const{
		return cost<A.cost;
	}
}ee[6000];

int root(int x)
{
	if(Tree[x]==-1)return x;
	else
	{
		int tmp = root(Tree[x]);
		Tree[x] = tmp;
		return tmp;
	}
}

int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		if(n==0)break;
		//初始化
		 for(int i=1;i<=n;i++)Tree[i]=-1;
		 for(int i=1;i<=n*(n-1)/2;i++)
		 {
		 	int a,b,co;
		 	scanf("%d %d %d",&a,&b,&co);
		 	ee[i].a=a;
		 	ee[i].b=b;
		 	ee[i].cost=co;
		 }
		 sort(ee+1,ee+1+n*(n-1)/2);
		 int ans = 0;
		 for(int i=1;i<=n*(n-1)/2;i++)
		 {
		 	int x,y;
		 	x = root(ee[i].a);
		 	y = root(ee[i].b);
		 	if(x!=y)
		 	{
		 		Tree[x]=y;
		 		ans+=ee[i].cost;
			}	 
		 }
		 printf("%d\n",ans);//不要在printf这里写&了!! 
	}
	return 0;
 } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值