Kruskal_最小生成树_算法

版权声明:欢迎大佬批评指正!O(∩_∩)O https://blog.csdn.net/wyh1618/article/details/83003347

//注释尽早补上

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<malloc.h>
#define INF 99999
#define MAXV 100
using namespace std;

typedef struct
{
    int no;
}VertexType;

typedef struct
{
    int edges[100][100];
    int n,e;
    VertexType vexs[100];
}MatGraph;

typedef struct
{
    int u;
    int v;
    int w;
}Edge;

void sssort(Edge E[100],int k)
{
    for(int i=0;i<k;i++)
    {
        for(int j=0;j<k-1;j++)
        {
            if(E[j].w>E[j+1].w)
            {
                swap(E[j],E[j+1]);
            }
        }
    }
}

void CreatMat(MatGraph &g,int A[6][10],int n,int e)
{
    int i,j;
    g.n=n;
    g.e=e;
    for(i=0;i<g.n;i++)
    {
        for(j=0;j<g.n;j++)
        {
            g.edges[i][j]=A[i][j];
        }
    }
}

void DispMat(MatGraph g)
{
    int i,j;
    for(i=0;i<g.n;i++)
    {
        for(j=0;j<g.n;j++)
        {
            if(g.edges[i][j]!=INF)
            {
                printf("%4d",g.edges[i][j]);
            }
            else
            {
                printf("%4s","#");
            }
        }
        cout<<endl;
    }
}



void Kruskal(MatGraph &g)
{
    int i,j,k;
    int u1,v1,sn1,sn2;
    int vest[100];
    Edge E[110];
    k=0;
    for(i=0;i<g.n;i++)
    {
        for(j=0;j<=i;j++)
        {
            if(g.edges[i][j]!=0&&g.edges[i][j]!=INF)
            {
                E[k].u=i;
                E[k].v=j;
                E[k].w=g.edges[i][j];
                k++;
            }
        }
    }
    sssort(E,k);
    for(i=0;i<g.n;i++)
    {
        vest[i]=i;
    }
    k=1;
    j=0;
    while(k<g.n)
    {
        u1=E[j].u;
        v1=E[j].v;
        sn1=vest[u1];
        sn2=vest[v1];
        if(sn1!=sn2)
        {
            printf("Edge(%d,%d):%d\n",u1,v1,E[j].w);
            k++;
            for(i=0;i<g.n;i++)
            {
                if(vest[i]==sn2)
                {
                    vest[i]=sn1;
                }
            }
        }
        j++;
    }
}

int main()
{
    MatGraph g;
    int A[6][10]={
    {0,5,8,7,INF,3}, {5,0,4,INF,INF,INF},
    {8,4,0,5,INF,9}, {7,INF,5,0,5,6},
    {INF,INF,INF,5,0,1}, {3,INF,9,6,1,0}};
    CreatMat(g,A,6,10);
    DispMat(g);
    cout<<endl;
    Kruskal(g);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wyh1618/article/details/83003347