hdu 1233还是畅通工程(最小生成树+并查集)

解题思路:

这题主要是考察最小生成树把,在顺便在连通性上用到了并查集,我是用结构体来存图,然后在把路径长度排序,然后遍历结构体,如果没有连通,那么通过并查集来连通,然后加上长度。

AC代码:

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
struct haha
{
	int x;
	int y;
	int num;
};
struct haha p[5000];
bool cmp(haha x1,haha x2)
{
	return x1.num<x2.num;
}
int all=0;
int z1[105];
int road(int t)
{
	int t1=t,t2=t,t3;
	while(z1[t1]!=t1)
	{
		t1=z1[t1];
	}
	while(z1[t2]!=t2)
	{
		t3=z1[t2];
		z1[t2]=t1;
		t2=t3;
	}
	return t1;
}
int main(int argc, char *argv[]) {
	int a,c,d,e;
	double b;
	while(scanf("%d",&a)!=EOF)
	{
		if(a==0)
		{
			return 0;
		} 
		for(int n=1;n<=a;n++)
		{
			z1[n]=n;
		}
		for(int n=0;n<a*(a-1)/2;n++)
		{
			scanf("%d %d %d",&c,&d,&e);
			p[n].x=c;
			p[n].y=d;
			p[n].num=e;
		}
		sort(p,p+(a*(a-1)/2),cmp);
		for(int n=0;n<a*(a-1)/2;n++)
		{
			if(road(p[n].x)!=road(p[n].y))
			{
				all=all+p[n].num;
				z1[road(p[n].y)]=road(p[n].x);
			}
		}
		printf("%d\n",all);
		all=0;
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值