zoukankan      html  css  js  c++  java
  • 最小生成树之Kruskal算法

    问题:关键还是定义数据结构问题,还有如何把两个集合合并成一个。

    代码:

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    #define MAXV 20
    #define INFINITY 65535
    typedef struct node
    {
    	int from;
    	int to;
    	int weight;
    }WGraph;
    typedef struct map
    {
    	WGraph arr[MAXV];
    	int vexs,edges;
    }*Map;
    
    void createGraph(Map &map)                          //创建图
    {
    	int i;
    	cout<<"please input the edges and vexs:";
    	cin>>map->edges>>map->vexs;
    	for(i=0;i<map->edges;i++)
    	{
    		cout<<"please input from,to,weight of graph:";
    		cin>>map->arr[i].from>>map->arr[i].to>>map->arr[i].weight;
    	}
    }
    
    void showGraph(Map wg)
    {
        int i;
    	cout<<"the num of edges and vexs:";
    	cout<<wg->edges<<"   "<<wg->vexs<<endl;
    	for(i=0;i<wg->edges;i++)
    	{
    		cout<<"("<<wg->arr[i].from<<","<<wg->arr[i].to<<"   "<<wg->arr[i].weight<<")"<<endl;
    	}
    	cout<<endl;
    }
    
    void MST_Kruskal(Map map)
    {
    	int set[MAXV];
    	int min;
    	int i,j,k,s;
    	int temp;
    	int flag;                                 //访问标志
    	for(i=0;i<map->edges;i++)
    	{
    		set[i]=i;
    	}
    	for(j=0;j<map->vexs-1;j++)   //共有n-1条边
    	{
    		min=INFINITY;
    		for(k=0;k<map->edges;k++)                                //查找最小边
    		{
    			if(set[map->arr[k].from]!=set[map->arr[k].to])
    			{
    				if(map->arr[k].weight<min)
    				{
    				min=map->arr[k].weight;
    				temp=k;
    				}
    			}	
    		}
    		flag=set[map->arr[temp].to];
    		for(s=0;s<map->edges;s++)                        //把两个集合合并成一个集合
    		{
    			if(set[s]==flag)
    				set[s]=set[map->arr[temp].from];
    		}
    		cout<<"("<<map->arr[temp].from<<","<<map->arr[temp].to<<","<<map->arr[temp].weight<<")"<<endl;    //输出最小生成树
    
    	}
    
    }
    
    int main()
    {
    	Map map;
    	map=(Map)malloc(MAXV*sizeof(struct map));
    	cout<<"create the map:"<<endl;
    	createGraph(map);
    	cout<<"output the map";
    	showGraph(map);
    	cout<<"mst_kruskal :"<<endl;
    	MST_Kruskal(map);
    	cout<<endl;
    	return 0;
    }
    

     运行截图:

  • 相关阅读:
    IOptions、IOptionsMonitor、IOptionsSnapshot的区别
    基于 .NET 的 FluentValidation 验证教程
    挂载NFS网络文件系统教程
    gcc简要知识点
    二叉树遍历(前序、中序、后序、层次、广度优先、深度优先遍历)
    项目管理的一些知识总结
    Vue从零开发单页应用程序项目
    CRC校验原理
    Linux 文件搜索神器 find 实战详解
    Linux 三剑客之 grep、sed、awk 使用详解
  • 原文地址:https://www.cnblogs.com/xshang/p/3080055.html
Copyright © 2011-2022 走看看