prim算法:
1)思想: //创建edg[][]二维数组储存图表,low[i]记录未加入点到加入点集合的最小距离,visited数组标记某点是否已加入集合,en[i]表示使i加入Enew的点。(恩人节点)
已知V和E,求Vnew和Enew
初始时令:vnew={v1}
在v-vnew中找出和vnew中点距离最近的点,加入vnew,
2)步骤
step1: 取节点1加入集合vnew,标记visit[1]=1,由节点1初始化low[],en[];
step2:进行n-1次如下操作,每进行一次加入一个点到vnew
2.1 找出low[i]中最小值对应下标pos,
2.2 标记visit[pos]=1;
2.3 更新low[]
初始化–》找–》标记–》更新
void prim(int edg[][n],int low[],int visited[],int en[],int enew[][n])
{
int i,j,pos,min;
memset(visited,0,sizeof(visited));
visited[1]=1;pos=1;//取第一个点,分别标记和记录该点
for(i=1;i<=n;i++)
if(i!=pos)
{
low[i]=edg[pos][i]; //第一次给low数组赋值
en[i]=pos;
}
for(i=1;i<n;i++)//再运行n-1次
{
min=MaxInt;
for(j=1;j<=n;j++)//找出最小权值并记录位置
if(visited[j]==0&&min>low[j])
{
min=low[j];pos=j;
}
visited[pos]=1;//标记该点
for(j=1;j<=n;j++)//更新权值
if(visited[j]==0&&low[j]>map[pos][j])
{
low[j]=map[pos][j];
en[j]=pos;
}
}
memset(enew,0,sizeof(enew)); //二位数组enew初始化为0
for(i=2;i<=n;i++)
enew[en[i]][i]=1;//为1表示是最小生成树的边;
}