【DSA_Fall2020】4. Disjoint Set (Templates in C)

并查集、等价类、不相交集合

本文为本人学习过程中整理的学习笔记,想顺带学英语所以用英文呈现。发现错误还烦请指正。欢迎交流。

未经同意,请勿转载

Disjoint Set

Equivalence Relations

image-20201208140104268

Dynamic Equivalence Problem

image-20201208140845814

Disjoint Set

Pick a element to be the symbol of the disjoint set.

image-20201208141027001
Find

Return the root of the disjoint set structure.

  • Simple Find

    image-20201208143006689
    DisjSetType find(DisjSetType x, DisjSets s){
        while(s[x] > 0)
            x = s[x];
       	return x;
    }
    
  • Path Compression

    image-20201208143239838

    Visiting RED node with pointing all the upstream nodes to the root, which is slower for a single finding, but faster for a sequence of finding operations.

    Not compatible with union-by-height since it changes the heights. Just take “height” as an estimated rank.

    • Recursive Version

      DisjSetType Find(DisjSetType x, DisjSets s){
          if(s[x] <= 0)
              return x;
         	else
              return s[x] = find(s[x], s);
      }
      
    • Iterative Version

      DisjSetType Find (DisjSetType x, DisjSets s){
          DisjSetType root, trail, lead;
          for(root = x; s[root] > 0; root = s[root])
              ;
         	for(trail = x; trail != root; trail = lead){
              lead = s[trail];
              s[trail] = root;
          }
          root;
      }
      
Union
  • Simple Union

    void union(DisjSetType s1, DisjSetType s2, DisjSets s){
        s[find(s2)] = s[s1];
    }
    
  • Smart Union

    Store the size or height information as negative number (invalid index) in root.

    • Union by Size: Always change the smaller tree

      S[root] = -size_of_tree
      
    • Union by Height: Always change the shallow tree

      S[root] = -height_of_tree
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值