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

相关推荐
Tipriest_6 分钟前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现
c++·python·算法·二分法
晨晖21 小时前
顺序查找:c语言
c语言·开发语言·算法
LYFlied1 小时前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)
数据结构·算法·leetcode·动态规划
Salt_07282 小时前
DAY44 简单 CNN
python·深度学习·神经网络·算法·机器学习·计算机视觉·cnn
货拉拉技术2 小时前
AI拍货选车,开启拉货新体验
算法
MobotStone2 小时前
一夜蒸发1000亿美元后,Google用什么夺回AI王座
算法
Wang201220132 小时前
RNN和LSTM对比
人工智能·算法·架构
xueyongfu2 小时前
从Diffusion到VLA pi0(π0)
人工智能·算法·stable diffusion
永远睡不够的入2 小时前
快排(非递归)和归并的实现
数据结构·算法·深度优先
cheems95273 小时前
二叉树深搜算法练习(一)
数据结构·算法