| 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
相关推荐
阿Y加油吧11 分钟前
两道经典 DP 题:零钱兑换 & 单词拆分(完全背包 + 字符串 DP)疯狂打码的少年19 分钟前
有序线性表删除一个元素:顺序存储 vs 单链表,平均要移动多少个元素?y = xⁿ33 分钟前
20天速通LeetCode day07:前缀和载数而行5201 小时前
算法集训1:模拟,枚举,错误分析,前缀和,差分hehelm1 小时前
vector模拟实现Tina学编程2 小时前
[HOT 100]今日一练------划分字母区间RTC老炮2 小时前
RaptorQ前向纠错算法架构分析故事和你912 小时前
洛谷-数据结构1-1-线性表2m0_555762902 小时前
从原始信号到IQ图的数学公式推导靠沿2 小时前
【递归、搜索与回溯算法】专题四——综合练习