图论——题目汇总+代码总结(六)
作者:
就是要AC
,
2021-05-16 21:07:51
,
所有人可见
,
阅读 340
Kruskal
AcWing 859. Kruskal算法求最小生成树
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 200010;//SE问题,也可能出现在这里,一般就是边界问题
int n, m;
int p[N];
struct Edge
{
int a, b, w;
bool operator< (const Edge &W)const
{
return w < W.w;
}
}edges[N];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
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};
}
//直接写kruscal, 不用把他单独包起来了
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 = find(a), b = find(b);
if (a != b)
{
p[a] = b;
res += w;//最小生成树,所有树边的权重之和
cnt++; //当前加了多少条边
}
}
if (cnt < n - 1) puts("impossible");
else printf("%d\n", res);
return 0;
}