最小生成树的经典算法,用到了树与等价的知识,具体参见严蔚敏数据结构P175具体内容。
"head.h"
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX_VEX_NUM 20
#define MAX_EDGE_NUM MAX_VEX_NUM*MAX_VEX_NUM/2
class VexNode//顶点类记录一个顶点
{
public:
VexNode();
int father;//父节点位置
char name;//节点名字
int memnum;//当前节点所在集合中的元素个数
};
VexNode::VexNode()
{
father=-1;
memnum=1;
}
class VexBox//顶点集合类
{
public:
VexBox();
VexNode vexbox[MAX_VEX_NUM];
int vexnum;//顶点数目
};
VexBox::VexBox()
{
vexnum=0;
}
class EdgeNode//边节点类
{
public:
EdgeNode();
int vexnum1;//边连接的两个顶点的编号
int vexnum2;
int weight;//边的权重
};
EdgeNode::EdgeNode()
{
weight=0;
}
class EdgeBox//边的集合
{
public:
EdgeBox();
EdgeNode edgebox[MAX_EDGE_NUM];
int edgenum;
};
EdgeBox::EdgeBox()
{
edgenum=0;
}
class Kruskal//Kruskal算法实现类
{
public:
void GetKruskal();//接口函数
private:
void GetVex();//得到顶点信息
void GetEdge();//得到边的信息
void BuildTree();//建立生成树
int GetRoot(int);//得到以树表示的集合的根节点
VexBox v;
EdgeBox e;
};
void Kruskal::GetKruskal()//接口函数
{
GetVex();//得到顶点信息
GetEdge();//得到边的信息
BuildTree();;//建立生成树
}
void Kruskal::GetVex()//得到顶点信息
{
cout<<"Please Input Vertexes Of Graph :"<<endl<<endl;
char name;
while(cin>>name)
{
v.vexbox[v.vexnum++].name=name;
}
cin.clear();
}
bool Cmp(EdgeNode e1,EdgeNode e2)
{
if(e1.weight<e2.weight)
return true;
else
return false;
}
void Kruskal::GetEdge()//得到边的信息
{
cout<<"Please Input Edges Of Graph :"<<endl
<<"vexnum1 vexnum2 weight"<<endl<<endl;
int vexnum1,vexnum2,weight;
while(cin>>vexnum1>>vexnum2>>weight)
{
e.edgebox[e.edgenum].vexnum1=vexnum1;
e.edgebox[e.edgenum].vexnum2=vexnum2;
e.edgebox[e.edgenum].weight=weight;
e.edgenum++;
}
cin.clear();
sort(e.edgebox,e.edgebox+e.edgenum,Cmp);
}
int Kruskal::GetRoot(int i)//得到以树表示的集合的根节点
{
if(v.vexbox[i].father==-1)
return i;
else
return GetRoot(v.vexbox[i].father);
}
void Kruskal::BuildTree()//建立生成树
{
int root1,root2;
for(int i=0;i<e.edgenum;i++)
{
if((root1=GetRoot(e.edgebox[i].vexnum1))!=(root2=GetRoot(e.edgebox[i].vexnum2)))
{
cout<<v.vexbox[e.edgebox[i].vexnum1].name<<"<-->"<<v.vexbox[e.edgebox[i].vexnum2].name<<endl;
if(v.vexbox[root1].memnum<v.vexbox[root2].memnum)
{
v.vexbox[root1].father=root2;
v.vexbox[root2].memnum+=v.vexbox[root1].memnum;
}
else
{
v.vexbox[root2].father=root1;
v.vexbox[root1].memnum+=v.vexbox[root2].memnum;
}
if(v.vexbox[root2].memnum==v.vexnum)
return;
}
}
cout<<"Can't Build A Connected Graph !"<<endl<<endl;
}
"main.cpp"
#include"head.h"
int main()
{
Kruskal k;
k.GetKruskal();
system("pause");
}