一些灵巧的求并算法

 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值