| Prim
求
MST
| INIT: cost[][]
耗费矩阵
(inf
为无穷大
);
| CALL: prim(cost, n);
返回
-1
代表原图不连通
;
\*==================================================*/
#define
typec
int
// type of cost
const
typec inf = 0x3f3f3f3f;
// max of cost
int
vis[V]; typec lowc[V];
typec prim(typec cost[][V],
int
n)
// vertex: 0 ~ n-1
{
int
i, j, p;
typec minc, res = 0;
memset(vis, 0,
sizeof
(vis));
vis[0] = 1;
for
(i=1; i<n; i++) lowc[i] = cost[0][i];
for
(i=1; i<n; i++) {
minc = inf; p = -1;
for
(j=0; j<n; j++)
if
(0 == vis[j] && minc > lowc[j]) {
minc = lowc[j]; p = j;
}
if
(inf == minc)
return
-1;
//
原图不连通
res += minc; vis[p] = 1;
for
(j=0; j<n; j++)
if
(0 == vis[j] && lowc[j] > cost[p][j])
lowc[j] = cost[p][j];
}
return
res;
}
版权声明:本文为weixin_53666393原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。