Prim 求 MST| INIT: cost[][]耗费矩阵(inf为无穷大);

| 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;
}

相关推荐
小O的算法实验室10 小时前
2024年ESWA SCI1区TOP,异构无人机配送问题的集成多目标优化方法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
草履虫建模10 小时前
力扣算法 121. 买卖股票的最佳时机
算法·leetcode·职场和发展·贪心算法·动态规划·一次遍历
养军博客10 小时前
C语言五天速成(可用于蓝桥杯备考 难度中等偏下)
c语言·算法·蓝桥杯
爱尔兰极光10 小时前
LeetCode--有序数组的平方
算法·leetcode·职场和发展
jay神10 小时前
森林火灾检测数据集
算法·机器学习·目标跟踪
80530单词突击赢11 小时前
STLVector底层原理与高效运用
数据结构·算法
haluhalu.11 小时前
LeetCode---基础算法刷题指南
数据结构·算法·leetcode
iAkuya11 小时前
(leetcode)力扣100 58组合总和(回溯)
算法·leetcode·职场和发展
80530单词突击赢11 小时前
C++关联容器深度解析:set/map全攻略
java·数据结构·算法
m0_5613596711 小时前
代码热更新技术
开发语言·c++·算法