| 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;
}
Prim 求 MST| INIT: cost[][]耗费矩阵(inf为无穷大);
千秋TʌT2023-09-18 12:38
相关推荐
小O的算法实验室2 天前
2026年ASOC,基于深度强化学习的无人机三维复杂环境分层自适应导航规划方法,深度解析+性能实测郭涤生2 天前
STL vector 扩容机制与自定义内存分配器设计分析༾冬瓜大侠༿2 天前
vectorRicky111zzz2 天前
leetcode学python记录1汀、人工智能2 天前
[特殊字符] 第58课:两个正序数组的中位数liu****2 天前
第16届省赛蓝桥杯大赛C/C++大学B组(京津冀)汀、人工智能2 天前
[特殊字符] 第79课:分割等和子集汀、人工智能2 天前
[特殊字符] 第74课:完全平方数CoderCodingNo2 天前
【GESP】C++四、五级练习题 luogu-P1177 【模板】排序Proxy_ZZ02 天前
从零实现LDPC比特翻转译码器:C语言实战与底层逻辑解析