一些灵巧的求并算法

 1 class DisjSets
 2 {
 3 public:
 4     explicit DisjSets(int numElements);
 5     int find(int x)const;
 6     int find(int x);
 7     void unionSets(int root1, int root2);
 8 private:
 9     vector<int> s;
10 };
11 
12 
13 DisjSets::DisjSets(int numElements) : s(numElements)
14 {
15     for (int i = 0; i < s.size(); i++)
16         s[i] = -1;
17 }
18 
19 //下面是将两个集合并
20 void DisjSets::unionSets(int root1, int root2)
21 {
22     s[root2] = root1;
23 }
24 
25 //下面是寻找一个元素所在的集合
26 int DisjSets::find(int x) const
27 {
28     if (s[x] < 0)
29         return x;
30     else
31         return find(s[x]);
32 }
 1 //下面的是并集的一个变种,用于控制树的高度以及节点数量
 2 void DisjSets::unionSets(int root1, int root2)
 3 {
 4     if (s[root2] < s[root1])    //root2 is deeper
 5         s[root1] = root2;
 6     else
 7     {
 8         if (s[root1] == s[root2])
 9             s[root1]--;            //如果深度相同的话,再是root1的深度变得更深一点
10         s[root2] = root1;        //然后再让root2指向root1
11     }
12 }
1 //对上述并集程序使用了路径压缩之后,体现在find程序上的变化
2 int DisjSets::find(int x)const
3 {
4     if (s[x] < 0)
5         return x;
6     else
7         return s[x] = find(s[x]);
8 }
原文地址:https://www.cnblogs.com/-wang-cheng/p/4874173.html