//普里姆算法.cpp
#include<stdio.h>
#include<stdio.h>
#include<malloc.h>
#define MAX 30
typedef enum{DG,DN,UDG,UDN} Graphkind;
typedef struct arccell //定义表示弧的邻接矩阵
{
int adj;
int *info; //弧的相关信息
}arccell,adjmatrix[MAX][MAX];
typedef struct //定义一个图类型
{
int vexs[MAX];
adjmatrix arcs;
int vexnum,arcnum;
Graphkind kind;
}mgraph;
//用来标志最小权和已经并入u的顶点
typedef struct {
int adjvex;
int lowcost;
}closed;
closed closedge[MAX];
//找出数组中最小的元素
int minimum(closed *a)
{
int temp,mid;
temp=a[0].lowcost;
mid=0;
for(int i=1;i<MAX;++i)
if(temp>a[i].lowcost&&temp!=0&&a[i].lowcost!=0)
{
temp=a[i].lowcost;
mid=i;
}
return mid;
}
//找出值为v的顶点在图的存储数组中的索引
int locatevex(mgraph g,int v)
{
for(int i=0;i<g.vexnum;++i)
if(g.vexs[i]==v)return i;
}
int createUDN(mgraph &G) //构造无向图
{
int i,j,k;
int v1,v2,w;
printf("输入无向图的顶点个数和边的个数:/n");
scanf("%d%d",&G.vexnum,&G.arcnum);
printf("输入无向图的各顶点的值:/n");
for(i=0;i<G.vexnum;++i)
scanf("%d",&G.vexs[i]);
for(i=0;i<G.vexnum;++i)
for(j=0;j<G.vexnum;++j)
{G.arcs[i][j].adj=0;G.arcs[i][j].info=0;}
for(k=0;k<G.arcnum;++k)
{
printf("输入无向图边的两个关联顶点和该边的权值:/n");
scanf("%d%d%d",&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; //注意:不能写成G.arcs[i][j].adj=G.arcs[j][i].adj;
}
return 1;
}
void minispantree(mgraph G,int u)
{
int k,j,i;
k=locatevex(G,u);
//初始化标志数组
for(j=0;j<G.vexnum;++j)
if(j!=k)
{
closedge[j].adjvex=u;
closedge[j].lowcost=G.arcs[k][j].adj;
}
closedge[k].lowcost=0;
for(i=1;i<G.vexnum;++i)
{
k=minimum(closedge);
printf("*%d %d* ",G.vexs[k],closedge[k].lowcost);
closedge[k].lowcost=0;
for(j=0;j<G.vexnum;++j)
if(G.arcs[k][j].adj<closedge[j].lowcost)
{
closedge[j].adjvex=G.vexs[k];
closedge[j].lowcost=G.arcs[k][j].adj;
}
}
}
void main()
{
mgraph g;
createUDN(g);
minispantree(g,11);
}