0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-12-24 18:11:59 +00:00

859. Kruskal算法求最小生成树

https://www.acwing.com/problem/content/submission/code_detail/7029702/
This commit is contained in:
Baoshuo Ren 2021-08-10 16:36:35 +08:00 committed by Baoshuo Ren
parent 97605cd891
commit a0331f4bea
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

42
AcWing/859/859.cpp Normal file
View File

@ -0,0 +1,42 @@
#include <bits/stdc++.h>
using namespace std;
int n, m, fa[100005], res, cnt;
struct node {
int u, v, w;
bool operator<(const node x) const {
return w < x.w;
}
} g[200005];
int find(int x) {
return fa[x] = fa[x] != x ? find(fa[x]) : fa[x];
}
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> g[i].u >> g[i].v >> g[i].w;
}
sort(g, g + m);
for (int i = 1; i <= n; i++) {
fa[i] = i;
}
for (int i = 0; i < m; i++) {
g[i].u = find(g[i].u);
g[i].v = find(g[i].v);
if (g[i].u != g[i].v) {
fa[g[i].u] = g[i].v;
res += g[i].w;
cnt++;
}
}
if (cnt < n - 1) {
cout << "impossible" << endl;
} else {
cout << res << endl;
}
return 0;
}