《大话数据结构》最小生成树——Kruskal算法

本文详细解释了Kruskal算法用于寻找n个节点图的最小生成树的过程,包括边权值筛选、闭环避免策略及算法实现。
/*
	2014-6-24
	思想:n个节点的图中,只需要找到权值最小且不与现有边集合构成环的(n-1)条边,必成最小生成树。

	方案:将边的权值进行筛选,每次找到权值最小的边,补充道边集合中即可。

	难点:如何确保这些边不构成环——对每个边,让其起始节点是祖先,通过洄游寻根,如果祖先相同说明两个节点是“近亲”,会构成闭环:
	A-B-C-A三角形中:
	1. A-B边中确定B的祖先和父亲都是A;
	2. B-C边中,确定C的父亲是B,而B的父亲是A,故C的祖先也是A。
	3. A-C边中,C的祖先是A,A的祖先是A,故此时就能构成闭环。
*/
#include <iostream>
#include <queue>   
using namespace std;


typedef struct EdgeType{
	int begin;
	int end;
	int weight;
}EdgeType;


EdgeType edges[15]={
	{4,7,7},	{2,8,8},	{0,1,10},	{0,5,11},	{1,8,12},
	{3,7,16},	{1,6,16},	{5,6,17},	{1,2,18},	{6,7,19},
	{3,4,20},	{3,8,21},	{2,3,22},	{3,6,24},	{4,5,26}
};


int parent[9]={ 	/*初始化祖先,每个节点开始时刻均无祖先*/
	-1,-1,-1,
	-1,-1,-1,
	-1,-1,-1
};


int Find(int parent[],int father){

	while( parent[father]!=-1 )		/*只要双亲存在,就持续洄游,直到找到祖先*/
		father=parent[father];

	return father;

}

int num=1 ;

void Kruskal()
{
	int i,n,m;

	for(i=0;i<10;++i){

		m=Find(parent,edges[i].begin);
		n=Find(parent,edges[i].end);

		if(m!=n){
			parent[n]=m;	
			printf("%d: (%d,%d) %d\n",num++,edges[i].begin,edges[i].end,edges[i].weight);
		}

	}

}


int main(void)
{    
	cout<<"hello"<<endl;
	Kruskal();

	cout<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值