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


    /*
    	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
    ",num++,edges[i].begin,edges[i].end,edges[i].weight);
    		}
    
    	}
    
    }
    
    
    int main(void)
    {    
    	cout<<"hello"<<endl;
    	Kruskal();
    
    	cout<<endl;
    	return 0;
    }
    

  • 相关阅读:
    导入导出通用库
    镜像下载地址
    后端请求接口的几种方式
    获取本机的mac地址
    Arduino串口的一些高级用法
    手机与Arduino蓝牙串口通讯实验及完整例程
    ARDUINO+MCP2515实现CAN通讯接收
    Arduino IIC 主从设备连接通信
    上位机与单片机的通信问题
    NRF24L01多对一、多通道通讯关键代码
  • 原文地址:https://www.cnblogs.com/sjw1357/p/3863999.html
Copyright © 2020-2023  润新知