最小生成树之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;
}

 运行截图:

posted @   xshang  阅读(145)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示