• 带权并查集的适用前提:维护的关系具有可传递性。

  • 带权并查集操作需保证的条件:执行了函数 anc 或进行合并的节点的所有信息一定会被更新。

注意事项:无。

Luogu P2024 [NOI2001] 食物链

代码:

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
62
63
#include<bits/stdc++.h>
using namespace std;
const int MAXn = 5e4;

template <typename T>
inline void read(T &a) {
char c;for (c = getchar(); (c < '0' || c > '9') && c != '-'; c = getchar());bool f = c == '-';T x = f ? 0 : (c ^ '0');for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) {x = x * 10 + (c ^ '0');}a = f ? -x : x;
}
template <typename T, typename ...Argv>
inline void read(T &a, Argv &...argv) {
read(a), read(argv...);
}

inline int addmod(int x) {
return (x >= 3) ? x - 3 : x;
}
inline int redmod(int x) {
return (x < 0) ? x + 3 : x;
}

int fa[MAXn + 10];
int dis[MAXn + 10];
void init(int n) {
for (int i = 1; i <= n; ++i) {
fa[i] = i;
dis[i] = 0;
}
}
int anc(int x) {
if (fa[x] == x) {
return x;
} else {
int ancc = anc(fa[x]);
dis[x] = addmod(dis[fa[x]] + dis[x]);
fa[x] = ancc;
return ancc;
}
}

int n, m;

int ans;
signed main() {
read(n, m);
init(n);
for (int i = 1, opt, x, y; i <= m; ++i) {
read(opt, x, y);
if (x > n || y > n) {
++ans;
continue;
}
--opt;
int ancx = anc(x), ancy = anc(y);
if (ancx == ancy) {
if (redmod(dis[x] - dis[y]) != opt) ++ans;
} else {
fa[ancx] = ancy;
dis[ancx] = addmod(redmod(opt - dis[x]) + dis[y]);
}
}
printf("%d\n", ans);
return 0;
}