AcWing 859. Kruskal算法求最小生成树
原题链接
简单
作者:
sky-koi
,
2024-12-12 10:27:59
,
所有人可见
,
阅读 2
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
struct edge {
int u, v, w;
bool operator<(const edge &t) const {
return w < t.w;
}
}e[N * 2];
int d[N];
bool vis[N];
int fa[N];
int ans, cnt;
int n, m;
int find(int x) {
if (fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
bool kruskal() {
for (int i = 1; i <= n; i++)
fa[i] = i;
sort(e, e + m);
for (int i = 0; i < m; i++) {
int x = find(e[i].u);
int y = find(e[i].v);
if (x != y) {
ans += e[i].w;
cnt++;
fa[x] = y;
}
}
return cnt == n - 1;
}
int main()
{
scanf("%d%d", &n, &m);
int u, v, w;
for (int i = 0; i <m; i++) {
scanf("%d%d%d", &u, &v, &w);
e[i] = {u, v, w} ;
e[i] = {v, u, w};
}
if (kruskal())
cout << ans << endl;
else
cout << "impossible" << endl;
return 0;
}