| 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
相关推荐
xwz小王子2 分钟前
Nature Communications从结构到功能:基于Kresling折纸的多模态微型机器人设计luj_17682 分钟前
从R语言想起的,。。。计算机安禾11 分钟前
【数据结构与算法】第29篇:红黑树原理与C语言模拟生信研究猿17 分钟前
94. 二叉树的中序遍历 (二叉树遍历整理)挂科边缘18 分钟前
image-restoration-sde复现,图像修复,使用均值回复随机微分方程进行图像修复,ICML 20232301_8227032018 分钟前
开源鸿蒙跨平台Flutter开发:血氧饱和度数据降噪:基于滑动窗口的滤波算法优化-利用动态列队 (Queue) 与时间窗口平滑光电容积脉搏波 (PPG)Vin0sen20 分钟前
算法-线段树与树状数组sycmancia24 分钟前
QT——计算器核心算法倦王26 分钟前
力扣日刷45炽烈小老头29 分钟前
【 每天学习一点算法 2026/04/06】常数时间插入、删除和获取随机元素