今天又重新回顾了一下忘得差不多的并查集:下边是转的,再加上一道hdu的并查集入门题。
文章作者:yx_th000 文章来源:Cherish_yimi (http://www.cnblogs.com/cherish_yimi/) 转载请注明,谢谢合作。
[本文新址: http://www.ahathinking.com/archives/10.html ]
昨天和今天学习了并查集和trie树,并练习了三道入门题目,理解更为深刻,觉得有必要总结一下,这其中的内容定义之类的是取自网络,操作的说明解释及程序的注释部分为个人理解。并查集学习:
l 并查集:(union-find sets)
一种简单的用途广泛的集合. 并查集是若干个不相交集合,能够实现较快的合并和判断元素所在集合的操作,应用很多,如其求无向图的连通分量个数等。最完美的应用当属:实现Kruskar算法求最小生成树。
l 并查集的精髓(即它的三种操作,结合实现代码模板进行理解):
1、Make_Set(x) 把每一个元素初始化为一个集合
初始化后每一个元素的父亲节点是它本身,每一个元素的祖先节点也是它本身(也可以根据情况而变)。
2、Find_Set(x) 查找一个元素所在的集合
查找一个元素所在的集合,其精髓是找到这个元素所在集合的祖先!这个才是并查集判断和合并的最终依据。
判断两个元素是否属于同一集合,只要看他们所在集合的祖先是否相同即可。
合并两个集合,也是使一个集合的祖先成为另一个集合的祖先,具体见示意图
3、Union(x,y) 合并x,y所在的两个集合
合并两个不相交集合操作很简单:
利用Find_Set找到其中两个集合的祖先,将一个集合的祖先指向另一个集合的祖先。如图
l 并查集的优化
1、Find_Set(x)时 路径压缩
寻找祖先时我们一般采用递归查找,但是当元素很多亦或是整棵树变为一条链时,每次Find_Set(x)都是O(n)的复杂度,有没有办法减小这个复杂度呢?
答案是肯定的,这就是路径压缩,即当我们经过"递推"找到祖先节点后,"回溯"的时候顺便将它的子孙节点都直接指向祖先,这样以后再次Find_Set(x)时复杂度就变成O(1)了,如下图所示;可见,路径压缩方便了以后的查找。
2、Union(x,y)时 按秩合并
即合并的时候将元素少的集合合并到元素多的集合中,这样合并之后树的高度会相对较小。
l 主要代码实现

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

hdu 1232畅通工程http://acm.hdu.edu.cn/showproblem.php?pid=1232
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 int father[1010]; 5 int n, m, ans; 6 void make_set(int *a) 7 { 8 for (int i = 1; i <= n; ++i) 9 father[i] = i; 10 } 11 int find(int n) 12 { 13 if (n != father[n]) 14 father[n] = find(father[n]); 15 return father[n]; 16 } 17 void Union(int x, int y) 18 { 19 int fx = find(x), fy = find(y); 20 if (fx != fy) 21 { 22 father[fx] = fy; 23 --ans; 24 } 25 } 26 int main() 27 { 28 while (scanf("%d %d", &n, &m) != EOF && n) 29 { 30 ans = n - 1; 31 make_set(father); 32 while (m--) 33 { 34 int x, y; 35 scanf("%d %d", &x, &y); 36 Union(x, y); 37 } 38 printf("%d\n", ans); 39 } 40 system("pause"); 41 return 0; 42 }
hdu 1213 How Many Tables
1 #include <iostream> 2 #include <cstdio> 3 int father[1010]; 4 int n, m; 5 int make(int *a) 6 { 7 for (int i = 1; i <= n; ++i) 8 a[i] = i; 9 } 10 int find(int x) 11 { 12 if (x != father[x]) 13 father[x] = find(father[x]); 14 return father[x]; 15 } 16 void Union(int x, int y) 17 { 18 int fx = find(x), fy = find(y); 19 if (fx != fy) 20 father[fx] = fy; 21 } 22 int main() 23 { 24 int T; 25 scanf("%d", &T); 26 while (T--) 27 { 28 scanf("%d %d", &n, &m); 29 make(father); 30 while (m--) 31 { 32 int a, b; 33 scanf("%d %d", &a, &b); 34 Union(a, b); 35 } 36 int ans = 0; 37 for (int i = 1; i <= n; ++i) 38 if (father[i] == i) 39 ++ans; 40 printf("%d\n", ans); 41 } 42 system("pause"); 43 return 0; 44 }