HDU 1233 (最小生成树) 用并查集实现kruskal

题目很简单,不过有些细节要注意

#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000

struct edge1
{
	int x,y;
	int weigh;
}edge[MAX];

int father[MAX];


bool cmp(edge1 a, edge1 b)  
{  
	return a.weigh < b.weigh;  
}  



void init(int n)
{
	for(int i=0;i<=n;i++)       //这里要注意,如果写成i<n,那么就会WA,原因是第N个数没有开辟出节点,看清题意,他是从1...N,我错了半天才找出来
	{
		father[i]=i;
	}
}

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



void union_set(int x,int y)
{
	father[y]=x;
}



void main()
{
	int N,i,a,b, sum,M;
	while(cin>>N)
	{
		if(N==0) break;
		init(N);
		 sum=0;
		 M=N*(N-1)/2;
		for(i=0;i<M;i++)
		{
			cin>>edge[i].x>>edge[i].y>>edge[i].weigh;

		}

		sort(edge,edge+M,cmp);


		for(i=0;i<M;i++)
		{
			a=find_set(edge[i].x);
			b=find_set(edge[i].y);
			if(a!=b)
			{
				union_set(a,b);
				sum+=edge[i].weigh;
			}
		}
		cout<<sum<<endl;
	}
}


 

这样写可能有些别扭,我们干脆把数组从下标“1”开始存储

#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000

struct edge1
{
	int x,y;
	int weigh;
}edge[MAX];

int father[MAX];


bool cmp(edge1 a, edge1 b)  
{  
	return a.weigh < b.weigh;  
}  



void init(int n)
{
	for(int i=1;i<=n;i++)
	{
		father[i]=i;
	}
}

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



void union_set(int x,int y)
{
	father[y]=x;
}



void main()
{
	int N,i,a,b, sum,M;
	while(cin>>N)
	{
		if(N==0) break;
		init(N);
		 sum=0;
		 M=N*(N-1)/2;
		for(i=1;i<=M;i++)
		{
			cin>>edge[i].x>>edge[i].y>>edge[i].weigh;

		}

		sort(edge+1,edge+1+M,cmp);


		for(i=1;i<=M;i++)
		{
			a=find_set(edge[i].x);
			b=find_set(edge[i].y);
			if(a!=b)
			{
				union_set(a,b);
				sum+=edge[i].weigh;
			}
		}
		cout<<sum<<endl;
	}
}


下面附上用冒泡法写的算法,不过没有AC过,超时间

#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 10000

struct edge1
{
	int x,y;
	int weigh;
}edge[MAX];

int father[MAX];


bool cmp(edge1 a, edge1 b)  
{  
	return a.weigh < b.weigh;  
}  



void init(int n)
{
	for(int i=1;i<=n;i++)
	{
		father[i]=i;
	}
}

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



void union_set(int x,int y)
{
	father[y]=x;
}



void main()
{
	int N,i,a,b, sum,M;
	while(cin>>N)
	{
		if(N==0) break;
		init(N);
		 sum=0;
		 M=N*(N-1)/2;
		for(i=1;i<=M;i++)
		{
			cin>>edge[i].x>>edge[i].y>>edge[i].weigh;

		}

		sort(edge+1,edge+1+M,cmp);


		for(i=1;i<=M;i++)
		{
			a=find_set(edge[i].x);
			b=find_set(edge[i].y);
			if(a!=b)
			{
				union_set(a,b);
				sum+=edge[i].weigh;
			}
		}
		cout<<sum<<endl;
	}
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值