码迷,mamicode.com
首页 > 其他好文 > 详细

最小生成树

时间:2014-12-17 16:33:51      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:c   搜索   存储   

# include <stdio.h>
# define MAX_VERTEX_NUM 20
# define INFINITY 32768
# define Error -1
# define OK 1

typedef int AdjType;
typedef enum{DG,DN, UDG,UDN} GraphKind;
typedef char VertexData;
struct
{
 VertexData adjvex;
 int lowcost;
}closedge[MAX_VERTEX_NUM];
typedef struct ArcNode
{
 AdjType adj;
// OtherInfo info;
}ArcNode;

typedef struct
{
 VertexData vertex[MAX_VERTEX_NUM];
 ArcNode arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
 int vernum, arcnum;
 GraphKind kind;
}AdjMatrix;

int LocateVertex(AdjMatrix *g, VertexData v)        //求顶点位置函数
{
 int j = Error, k;
 for (k = 0; k <g->vernum; k++)
  if (g->vertex[k] == v)
  {
   j = k;break;
  }
  return j;
}

int CreateDN(AdjMatrix *g)               //创建图的邻接矩阵
{
 int i,j,k,weight;
 VertexData v1, v2;
 printf("请输入图的顶点数和弧数\n");
 scanf("%d%d", &g->vernum, &g->arcnum);
 for (i = 0; i < g->vernum;i++)
  for (j = 0; j < g->vernum; j++)
   g->arcs[i][j].adj = INFINITY;
 printf("请输入图的顶点\n");
 getchar();
 for (i = 0; i < g->vernum; i++)
  scanf("%c", &g->vertex[i]);
 printf("请输入每条弧的两个顶点及权值\n");
 getchar();
 for (k = 0; k < g->arcnum; k++)
 {
  scanf("%c%c%d%c", &v1,&v2,&weight);
  i = LocateVertex(g,v1);
  j = LocateVertex(g,v2);
  g->arcs[i][j].adj = weight;
  g->arcs[j][i].adj = weight;
 }
/* for (i = 0; i<g->vernum  ;i++)
 {
  for (k=0; k < g->vernum  ;k++)
   printf("%d     ",g->arcs[i][k].adj);
  printf("\n");
 }
*/ return OK;
}

int Minium(AdjMatrix *g)          //找去closedge[]中最小边的信息
{
 int i,index,sum = INFINITY;
 for (i = 0; i < g->vernum; i++)
  if (closedge[i].lowcost != 0 && sum > closedge[i].lowcost)
  {
   sum = closedge[i].lowcost;
   index = i;
  }
 return index;

}
void  MiniSpanTree_prim(AdjMatrix *g,VertexData u)            //普利姆算法(最小生成树)
{
 int i,k,k0,j;
 VertexData v0,u0;
 k = LocateVertex(g,u);
 closedge[k].lowcost = 0;
 for (i = 0; i < g->vernum ; i++)
  if (i!= k)
  {
   closedge[i].adjvex = u;
   closedge[i].lowcost = g->arcs[k][i].adj;
  }
 printf("最小生成树的边为\n");
 for (j = 1; j < g->vernum ; j++)
 {
  k0 = Minium(g);
  u0 = closedge[k0].adjvex;
  v0 = g->vertex[k0];
  printf("%c%c\n",u0,v0);
  closedge[k0].lowcost = 0;
  for (i = 0; i < g->vernum ; i++)
   if (g->arcs[k0][i].adj < closedge[i].lowcost)
   {
    closedge[i].lowcost = g->arcs[k0][i].adj;
     closedge[i].adjvex = v0;
   }
 }
}
int main(void)
{
 VertexData u;
 AdjMatrix g;
 CreateDN(&g);
 printf("请输入最小生成树的开始顶点\n");
 scanf("%c", &u);
 MiniSpanTree_prim(&g,u);

 return 0;
}

最小生成树

标签:c   搜索   存储   

原文地址:http://blog.csdn.net/java_oracle_c/article/details/41981633

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!