| 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
相关推荐
知识浅谈1 小时前
DeepSeek V4 和 GPT-5.5 在同一天发布了??我也很懵,但对比完我悟了DeepModel2 小时前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法田梓燊2 小时前
力扣:19.删除链表的倒数第 N 个结点简简单单做算法3 小时前
基于GA遗传优化双BP神经网络的时间序列预测算法matlab仿真guygg884 小时前
利用遗传算法解决列车优化运行问题的MATLAB实现武藤一雄4 小时前
19个核心算法(C#版)sali-tec4 小时前
C# 基于OpenCv的视觉工作流-章52-交点查找yu85939585 小时前
MATLAB连续线性化模型预测控制(SL-MPC)ytttr8735 小时前
基于ACADO工具包的自主车道跟踪与避障MPC控制