AcWing 859. Kruskal算法求最小生成树
原题链接
简单
作者:
昼最长
,
2020-04-12 09:24:37
,
所有人可见
,
阅读 535
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010, M = 200010, INF = 0x3f3f3f3f;
int n, m;
int p[N];
struct Edge
{
int a, b, w;
bool operator< (const Edge &W) const
{
return w < W.w;
}
}edges[M];
int find(int x)
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int kruskal()
{
//给所有边按权重大小排序
sort(edges, edges + m);
//初始化并查集
for(int i = 1; i <= n; i ++) p[i] = i;
int res = 0, cnt = 0;
//枚举每条边,因为已经排好序,所以是从小到大枚举
for(int i = 0; i < m; i ++)
{
int a = edges[i].a, b = edges[i].b, w = edges[i].w;
//找到a和b的祖宗节点,即判断a和b是否在一个连通块
a = find(a), b = find(b);
//如果不在就连起来
if(a != b)
{
p[a] = b;
res += w;
cnt ++;
}
}
if(cnt < n - 1) return INF;
return res;
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 0; i < m; i ++)
{
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
edges[i] = {a, b, w};
}
int t = kruskal();
if(t == INF) puts("impossible");
else printf("%d\n", t);
return 0;
}