贪心算法之prim算法

来源:互联网 发布:java utf 16le 编辑:程序博客网 时间:2024/06/05 18:35

算法思想

               首先置S={1},然后只要S是V的真子集,就做如下的贪心选择:选择满足条件i属于S,j属于V-S,且edge[i][j]是最小的边,就将其顶点j添加到S中,这个过程一直进行到S=V时为止,在这个过程中,选取到的所有边恰好构成G的一颗最小生成树。



#include<stdio.h>#define INFINITY 5000typedef char VertexType;typedef int EdgeType;#define MAX 100//定义数组大小typedef struct {VertexType vexs[MAX];EdgeType edges[MAX][MAX];int vexnum;//记录图的顶点数int arcnum;//记录图的边或弧的条数}AdjMatrix;//创建图的邻接矩阵AdjMatrix CreatGraph_Matrix(){AdjMatrix G;int i,j,k;int weight;printf("please input graph's vexnum and arcnum:\n");scanf("%d,%d",&G.vexnum,&G.arcnum);    setbuf(stdin,NULL);for(i=1;i<=G.vexnum;i++){scanf("%c",&G.vexs[i]); setbuf(stdin,NULL);}setbuf(stdin,NULL);for(i=1;i<=G.vexnum;i++)for(j=1;j<=G.vexnum;j++)G.edges[i][j]=INFINITY;for(k=1;k<=G.arcnum;k++){printf("please input NO.%d edge's start,end and weight:\n",k);scanf("%d,%d,%d",&i,&j,&weight);G.edges[i][j]=weight;G.edges[j][i]=weight;}return G;}void prim(AdjMatrix G){int lowcost[MAX];int closest[MAX];bool s[MAX];s[1]=true;//初始化lowcost[]for(int i=2;i<=G.vexnum;i++){lowcost[i]=G.edges[1][i];closest[i]=1;s[i]=false;}for(int j=1;j<G.vexnum;j++){int min=INFINITY;int u=1;//找到lowcost[]最小值for(int k=2;k<=G.vexnum;k++)if(lowcost[k]<min&&!s[k]){min=lowcost[k];u=k;}printf("%d  %d\n",u,closest[u]);s[u]=true;//为贪心选择做准备for(int m=2;m<=G.vexnum;m++)//若存在其他点到当前源点距离小于到最初源点的距离,则更新,因为我会贪心选择每次距离当前源点最小的if(G.edges[u][m]<lowcost[m]&&!s[m]){lowcost[m]=G.edges[u][m];closest[m]=u;}}}int main(){AdjMatrix G=CreatGraph_Matrix();prim(G);return 0;}


0 0
原创粉丝点击