7. 并查集
习题
#30011
⚡4⏳4
实现支持动态合并和连通性查询的整数并查集:
c
#include <stdbool.h>
#include <stddef.h>
typedef struct IntDisjointSet IntDisjointSet;
IntDisjointSet *int_dsu_create(size_t count);
void int_dsu_destroy(IntDisjointSet *set);
bool int_dsu_union(
IntDisjointSet *set,
size_t left,
size_t right,
bool *out_merged
);
bool int_dsu_same(
const IntDisjointSet *set,
size_t left,
size_t right,
bool *out_same
);
bool int_dsu_component_size(
const IntDisjointSet *set,
size_t element,
size_t *out_size
);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
要求:
- 初始时每个元素单独成集合;下标必须小于
count。 union使用按大小或按秩合并,并查找时进行路径压缩。- 重复合并成功返回并设置
*out_merged = false;失败时不得修改输出对象和集合结构。 destroy(NULL)安全;count == 0可以创建空集合。- 分摊时间复杂度应达到
,并说明所维护的不变式。