0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-27 17:16:28 +00:00

H1004. 【模板】最小生成树

https://hydro.ac/record/6157b1eead4d340581846fba
This commit is contained in:
Baoshuo Ren 2021-10-02 09:14:08 +08:00 committed by Baoshuo Ren
parent 29e50be31a
commit a9ea25dbd1
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

41
Hydro/H1004/H1004.cpp Normal file
View File

@ -0,0 +1,41 @@
#include <bits/stdc++.h>
using namespace std;
int n, m, fa[100005], cnt;
long long res;
struct node {
int u, v;
long long 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++;
}
}
cout << res << endl;
return 0;
}