AcWing 858. Prim算法求最小生成树
原题链接
简单
作者:
昼最长
,
2020-04-12 09:23:24
,
所有人可见
,
阅读 603
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510, INF = 0x3f3f3f3f;
int n, m;
int g[N][N];
int dist[N];
bool st[N];
int prim()
{
memset(dist, 0x3f, sizeof dist);
int res = 0;
for (int i = 0; i < n; i ++)
{
//找到当前集合外里集合最近的点
int t = -1;
for (int j = 1; j <= n; j ++)
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
//判断所有点是否连通,不能连通则不能构成最小生成树
if (i && dist[t] == INF) return INF;
//第一个点不能加进来
if (i) res += dist[t];
st[t] = true;
//用离目前集合最近的点来更新其他点
for (int j = 1; j <= n; j ++)
dist[j] = min(dist[j], g[t][j]);
}
return res;
}
int main()
{
scanf("%d%d", &n, &m);
memset(g, 0x3f, sizeof g);
while (m --)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
g[a][b] = g[b][a] = min(g[a][b], c);
}
int t = prim();
if(t == INF) puts("impossible");
else printf("%d\n", t);
return 0;
}