| 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
相关推荐
daad77713 小时前
std::vector insert炽烈小老头13 小时前
【每天学习一点算法 2026/04/07】快乐数计算机安禾13 小时前
【数据结构与算法】第31篇:排序概述与插入排序网路末端遗传因子13 小时前
CHO细胞培养中高乳酸与低产量的模式识别与分析阿Y加油吧13 小时前
LeetCode 中等难度 | 回溯法经典题解:组合总和 & 括号生成im_AMBER13 小时前
Leetcode 153 课程表 | 腐烂的橘子paeamecium13 小时前
【PAT甲级真题】- Reversing Linked List (25)田梓燊13 小时前
leetcode 73ZPC821013 小时前
相机接入ROS2 流程及问题排查2501_9403152613 小时前
【无标题】两个相同字符串中不同字符的个数