#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<algorithm>
#define INF 32767
#define MAXV 6
using namespace std;
typedef char InfoType;//图
typedef struct
{
int no;
InfoType info;
}VertexType;
typedef struct
{
int edges[MAXV][MAXV];
int n,e;
VertexType vexs[MAXV];
}MatGraph;
void CreateMat(MatGraph &g,int A[MAXV][MAXV],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)
cout<<" "<<g.edges[i][j]<<" ";
else
cout<<" "<<"…";
}
cout<<endl;
}
}
struct edge//Kruckal
{
int weight;
int u,v;
}bian[11];
bool cmp(edge a,edge b)
{
return a.weight<b.weight;
}
void Kruskal(int n,edge bian[],int c[6][6])
{
int nodeset[n];
int count=1;
bool flag[n+1];
for(int i=0;i<n;i++)
{
nodeset[i]=i;
flag[i]=false;
for(int j=0;j<n;j++)
{
if(c[i][j]<INF&&c[i][j]>0)
{
bian[count].u=i;
bian[count].v=j;
bian[count].weight=c[i][j];
count++;
}
}
}
sort(bian+1,bian+count,cmp);
count=1;
int edgeset=0;
int w=0;
while(edgeset<(n-1))
{
if((!flag[bian[count].u])&&flag[bian[count].v])
{
w=w+bian[count].weight;
edgeset++;
flag[bian[count].u]=true;
nodeset[bian[count].u]=nodeset[bian[count].v];
}
else if(flag[bian[count].u]&&(!flag[bian[count].v]))
{
w=w+bian[count].weight;
edgeset++;
flag[bian[count].v]=true;
nodeset[bian[count].v]=nodeset[bian[count].u];
}
else if((!flag[bian[count].u])&&(!flag[bian[count].v]))
{
w=w+bian[count].weight;
edgeset++;
flag[bian[count].u]=true;
flag[bian[count].v]=true;
nodeset[bian[count].v]=nodeset[bian[count].u];
}
else
{
if(nodeset[bian[count].u]!=nodeset[bian[count].v])
{
w=w+bian[count].weight;
edgeset++;
int tmp=nodeset[bian[count].v];
for(int i=0;i<n;i++)
{
if(nodeset[i]==tmp)
nodeset[i]=nodeset[bian[count].u];
}
}
}
count++;
}
cout<<"最小生成树有"<<edgeset<<"条边,权值和为"<<w<<"。"<<endl;
}
int main()
{
MatGraph g;
int A[MAXV][MAXV]=
{
{0,6,1,5,INF,INF},{6,0,5,INF,3,INF},{1,5,0,5,6,4},
{5,INF,5,0,INF,2},{INF,3,6,INF,0,6},{INF,INF,4,2,6,0}
};
int n=6,e=10;
int visited[5];
for(int i=0;i<5;i++)
visited[i]=0;
CreateMat(g,A,n,e);
cout<<"邻接矩阵为:"<<endl;
DispMat(g);
Kruskal(n,bian,A);
return 0;
}
仅作留档。