注册 登录
编程论坛 数据结构与算法

本人自己写的最小生成树的算法,高手来看一下

qq8801103 发布于 2010-06-03 11:48, 975 次点击
#include "stdio.h"
#define max 20
typedef int Status;
typedef struct ArcCell{
    int adj;
}ArcCell,AdjMatrix[max][max];
typedef struct{
  int  vexs[max];
  AdjMatrix arcs;
  int vexnum,arcnum;
}MGraph;
struct
{
    int adjvex;
   int lowcost;
}closedge[max];
Status CreateUDG(MGraph *G){
 int i,j,k;
 int v1,v2;  int w;
 printf("shuru dingdianshu and hushu:");
 scanf("%d,%d",&G->vexnum,&G->arcnum);
  printf("goujian dingdian xiangliang :");
 for(i=0;i<G->vexnum;i++)
   scanf("%d",&G->vexs[i]);
 printf("gouzao linjie juzhen :");
 for(i=0;i<G->vexnum;i++)
  for(j=0;j<G->vexnum;j++)
    G->arcs[i][j].adj=0;
 for(k=0;k<G->arcnum;k++){
   scanf("%d,%d,%d",&v1,&v2,&w);
   i=Locate(*G,v1);
   j=Locate(*G,v2);
   G->arcs[i][j].adj=w;
   G->arcs[j][i]=G->arcs[i][j];
 }
 return 1;
}

Status Locate(MGraph G,int v){
   int i;
   for(i=0;i<G.vexnum;i++)
      if(v==G.vexs[i])     return i;
   return -1;
}
int MinNum(MGraph G)
{
    int i,j=0,k=0,min=0;
    for(i=0; i<G.vexnum; i++)
    if(closedge[i].lowcost!=0)
    {
        min=closedge[i].lowcost;
        k=i;
        break;
    }
    for(j=i+1;j<G.vexnum;j++)
    if(closedge[j].lowcost!=0)
    {
        if(min>=closedge[j].lowcost)
        {
        min=closedge[j].lowcost;
        k=j;
        }
    }
    return k;
}
void MininSpanTreePrim(MGraph G,int V )
{
    int k=Locate(G,V);
    int j,i;
    for(j=0; j<G.vexnum; ++j )
    {
       if(j!=k)
       {
    closedge[j].lowcost =G.arcs[k][j].adj;
    closedge[j].adjvex=V;
       }
    }
    closedge[k].lowcost = 0;
    for(i=1; i<G.vexnum; ++i )
    {
    k=MinNum(G);
        closedge[k].lowcost = 0;
    printf("%d--%d ",closedge[k].adjvex,G.vexs[k]);
        for(j = 0; j<G.vexnum; ++j )
            if( closedge[j].lowcost > G.arcs[k][j].adj )
            {
                closedge[j].lowcost = G.arcs[k][j].adj;
        closedge[j].adjvex=G.vexs[k];
            }
    }
}
void main()
{
   MGraph G;   int v;
   int i,j;
   CreateUDG(&G);
   for(i=0;i<G.vexnum;i++){
    for(j=0;j<G.vexnum;j++)
      printf("%3d",G.arcs[i][j].adj);
    printf("\n");
   }
printf("shuru dian :");
    scanf("%d", &v);
    MininSpanTreePrim( G, v );
    printf("\n");

}

请高手改正
8 回复
#2
monk026982010-06-03 15:18
顶一个,
#3
qq88011032010-06-07 14:53
怎么没人来解啊  郁闷
#4
寒风中的细雨2010-06-07 19:37
for(i=0;i<G->vexnum;i++)
  for(j=0;j<G->vexnum;j++)
    G->arcs[i][j].adj=0;//改成 一个比较大的值(表示无穷)

Status Locate(MGraph G,int v) 的定义和Status CreateUDG(MGraph *G)的定义交换下顺序
#5
qq88011032010-06-12 15:15
我调试也 这么不对啊
#6
寒风中的细雨2010-06-12 17:19
只有本站会员才能查看附件,请 登录
#7
寒风中的细雨2010-06-12 17:20
改过之后  注意输入的格式   
#8
qq88011032010-08-19 15:38
知道了
#9
阝子健2011-07-07 19:45
好厉害
1