| 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
相关推荐
Tipriest_6 分钟前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现晨晖21 小时前
顺序查找:c语言LYFlied1 小时前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)Salt_07282 小时前
DAY44 简单 CNN货拉拉技术2 小时前
AI拍货选车,开启拉货新体验MobotStone2 小时前
一夜蒸发1000亿美元后,Google用什么夺回AI王座Wang201220132 小时前
RNN和LSTM对比xueyongfu2 小时前
从Diffusion到VLA pi0(π0)永远睡不够的入2 小时前
快排(非递归)和归并的实现cheems95273 小时前
二叉树深搜算法练习(一)