| 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
相关推荐
Hcoco_me2 小时前
大模型面试题17:PCA算法详解及入门实操跨境卫士苏苏2 小时前
亚马逊AI广告革命:告别“猜心”,迎接“共创”时代云雾J视界3 小时前
当算法试图解决一切:技术解决方案主义的诱惑与陷阱Xの哲學3 小时前
Linux Miscdevice深度剖析:从原理到实战的完整指南夏乌_Wx3 小时前
练题100天——DAY23:存在重复元素Ⅰ Ⅱ+两数之和立志成为大牛的小牛4 小时前
数据结构——五十六、排序的基本概念(王道408)沿着路走到底4 小时前
将数组倒序,不能采用reverse,算法复杂度最低IDIOT___IDIOT4 小时前
KNN and K-means 监督与非监督学习Hcoco_me5 小时前
大模型面试题18:t-SNE算法详解及入门实操