#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#define INFINITY 88
#define MAX_VERTEX_NUM 10
typedef int VRType;
typedef char VertexType;
/
typedef struct ArcCell
{
VRType adj; //图的权值
}ArcCell, AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct
{
VertexType vexs[MAX_VERTEX_NUM]; //顶点向量
AdjMatrix arcs;//邻接矩阵
int vexnum, arcnum; //顶点数,弧数
}MGraph;
///
typedef struct
{
VertexType adjvex;//顶点向量
VRType lowcost;//边长
}closedge[MAX_VERTEX_NUM];
//
void CreateGraph(MGraph &G);//创建矩阵存储
void Print(MGraph G);//输出创建矩阵
void MiniSpanTree_PRIM(MGraph G, VertexType u);//prime算法
int LocateVex(MGraph G, VertexType u);//求结点u的位置
int minimum(closedge close);//求结点的下一个顶点
//
void CreateGraph(MGraph &G){//采用数组表示法,构造无向图G
int i,j,k;
printf("请输入无向图的顶点数:/n");
scanf("%d",&G.vexnum);
printf("请输入无向图的弧数:/n");
scanf("%d",&G.arcnum);
printf("请输入各个顶点符号:/n");
for(i=0;i<G.vexnum;++i)//构造顶点向量
cin>>G.vexs[i];
for(i=0;i<G.vexnum;++i)//初始化邻接矩阵
for(j=0;j<G.vexnum;++j)
G.arcs[i][j].adj=INFINITY;
char v1,v2;//顶点
int w;//<v1,v2>的权值
for(k=1;k<=G.arcnum;++k){
cout<<"请输入第:"<<k<<"条边依附的俩个顶点以及权值:/n";
cin>>v1>>v2>>w;
i=LocateVex( G, v1);
j=LocateVex( G, v2);
G.arcs[i][j].adj=w;
G.arcs[j][i].adj=G.arcs[i][j].adj;
}
}
void MiniSpanTree_PRIM(MGraph G,VertexType u)
{
int i, j, k = 0;
closedge close;
k = LocateVex ( G, u );
for ( j = 0; j < G.vexnum; j++ )
{
if (j != k)
{
close[j].adjvex = u;
close[j].lowcost = G.arcs[k][j].adj;
}
}
cout<<j<<" fiusduasdfhul";
close[j].lowcost = INFINITY;
close[j].adjvex = '/0';//为了在minimum(close)中保证while循环的结束条件
close[k].lowcost = 0;
for (i = 1; i < G.vexnum; i++)
{
k = minimum(close);
cout<<close[k].adjvex<<"---->"<<G.vexs[k]<<" "<<close[k].lowcost<<endl;
close[k].lowcost = 0;
for (j=0; j<G.vexnum; j++)
{
if (G.arcs[k][j].adj < close[j].lowcost)
{
close[j].adjvex = G.vexs[k];
close[j].lowcost = G.arcs[k][j].adj;
}
}
}
}
int LocateVex(MGraph G,char v){//确定v在G中的位置
int i=-1;
for(i=0;i<G.vexnum;++i)
{
if(G.vexs[i]==v)
break;
else
continue;
}
return i;
}
void Print(MGraph G){
int i,j;
for(i=0;i<4;i++){
cout<<G.vexs[i]<<endl;
}
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
cout<<G.arcs[i][j].adj<<"/t";
cout<<endl;
}
}
int minimum(closedge close)
{
int i=0, client = INFINITY, j;
while(close[i].adjvex != '/0')
{
if (client > close[i].lowcost && close[i].lowcost != 0)
{
client = close[i].lowcost;
j = i;
}
i++;
}
return j;
}
int main(int argc, char* argv[])
{
MGraph G;
CreateGraph(G);
Print(G);
MiniSpanTree_PRIM(G,'a');
return 0;
}