0%

AtCoder Beginner Contest 214 D题(并查集)

题目链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;

const int N = 1e5 + 10;
const int M = 1e5 + 10;

struct node {
int u, v;
ll w;
}E[M];

ll fa[N], siz[N];
int n;

bool cmp(node a, node b) {
return a.w < b.w;
}

int Find(int x) {
if(fa[x] == x) return x;
return fa[x] = Find(fa[x]);
}

void merge(int x, int y) {
int a = Find(x);
int b = Find(y);
if(a != b) {
siz[a] += siz[b];
fa[b] = a;
}
}

int main() {
cin >> n;
for(int i = 1; i <= n; i++) {
fa[i] = i;
siz[i] = 1;
}
for(int i = 1; i <= n-1; i++) {
int u, v; ll w;
scanf("%d%d%lld", &u, &v, &w);
E[i] = {u, v, w};
}
sort(E + 1, E + n, cmp);
ll res = 0;
for(int i = 1; i <= n-1; i++) {
int u = E[i].u, v = E[i].v;
ll w = E[i].w;
if(Find(u) != Find(v)) {
res += w * siz[Find(u)] * siz[Find(v)];
merge(u, v);
}
}
printf("%lld\n", res);

return 0;
}
求大佬赏个饭