【模板】prim
C++版本:
Prim
int prim() {
fill(mincost + 1, mincost + V + 1, INF);
fill(vis + 1, vis + 1 + V, 0);
mincost[1] = 0;
int res = 0;
while (true) {
int v = -1;//v为当前路径(所连的节点)
for (int u = 1; u <= V; u++) {
//如果没被加入集合,并且找到更短的路径,更新当前路径
if (!vis[u] && (v == -1 || mincost[u] < mincost[v]))v = u;
}
if (v == -1)break;//所有点加入了集合
vis[v] = true;//把v加入集合
res += mincost[v];
//用加进的节点v更新mincost
for (int e = head[v]; e; e = eg[e].next) {
int u = eg[e].to;
mincost[u] = min(mincost[u], eg[e].cost);
}
}
return res;
}