并查集的小节

寒假就看了并查集的视频,可是一直没怎么用了,现在终于还是拾起,看了这方面的视频还是很好理解的;

看了挑战程序竞赛这本后,感觉大佬的思路就是简单,高效,可以首先写几个函数,分部实现各个功能,

按照思路:

1,格式化数组;

2,定义查找函数,便于找根;

3,定义联合函数,使需要联合的函数联合在一起,

4,定义判断函数,判断是否属于同一根

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 using namespace std;
 5 int par[1000], rak[1000];
 6 void init(int n)
 7 {
 8     for (int i = 0; i < n; i++)
 9     {
10         par[i] = i;
11         rak[i] = 0;
12     }
13 }
14 int find(int x)
15 {
16     if (par[x] == x)
17         return x;
18     else return par[x] = find(par[x]);
19 }
20 void unite(int x, int y)
21 {
22     x = find(x);
23     y = find(y);
24     if (rak[x] < rak[y])
25         par[x] = y;
26     else
27     {
28         par[y] = x;
29         if (rak[x] == rak[y]) rak[x]++;
30     }
31 }
32 bool same(int x, int y)
33 {
34     return find(x) == find(y);
35 }
36 int main()
37 {
38     init(10);
39     unite(1, 2);
40     unite(5, 1);
41 
42     unite(4, 6);
43     unite(6, 7);
44     unite(6, 5);
45     cout << same(1, 7) << endl;
46     cout << same(1, 6) << endl;
47     cout << same(1, 4) << endl;
48     cout << same(2, 5) << endl;
49     return 0;
50 }
原文地址:https://www.cnblogs.com/kangdong/p/8797471.html