| 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
相关推荐
2301_8194143021 分钟前
C++与区块链智能合约Zaly.27 分钟前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵做怪小疯子43 分钟前
蚂蚁暑期 319 笔试计算机安禾1 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现啊哦呃咦唔鱼1 小时前
LeetCode hot100-73 矩阵置零阿贵---1 小时前
C++构建缓存加速Queenie_Charlie1 小时前
最长回文子串 V2(Manacher算法)Evand J2 小时前
【MATLAB复现RRT(快速随机树)算法】用于二维平面上的无人车路径规划与避障,含性能分析与可视化一招定胜负2 小时前
机器学习+深度学习经典算法面试复习指南皮卡狮2 小时前
高阶数据结构:AVL树