簡體   English   中英

不相交集數據結構

[英]disjoint set data structure

這是findind不交集的代碼

    class disjoint_sets {
      struct disjoint_set {
      size_t parent;
      unsigned rank;
      disjoint_set(size_t i) : parent(i), rank(0) { }
       };
      std::vector<disjoint_set> forest;
       public:
       disjoint_sets(size_t n){
       forest.reserve(n);
        for (size_t i=0; i<n; i++)
         forest.push_back(disjoint_set(i));
        }
      size_t find(size_t i){
        if (forest[i].parent == i)
        return i;
         else {
        forest[i].parent = find(forest[i].parent);
        return forest[i].parent;
           }
          }
         void merge(size_t i, size_t j) {
          size_t root_i = find(i);
         size_t root_j = find(j);
          if (root_i != root_j) {
           if (forest[root_i].rank < forest[root_j].rank)
           forest[root_i].parent = root_j;
          else if (forest[root_i].rank > forest[root_j].rank)
          forest[root_j].parent = root_i;
           else {
            forest[root_i].parent = root_j;
             forest[root_j].rank += 1;
               }
            }
           }
            };

如果等級為eqaul,為什么我們要增加等級?? nma初學者不好意思,查找步驟在做什么?

因為在這種情況下-您添加的一棵樹是另一棵樹的“子樹”-這會使原始子樹增加其大小。

看下面的例子:

1           3
|           |
2           4

在上面,每棵樹的“等級”是2。
現在,假設1將成為新的統一根,您將獲得以下樹:

    1
   / \
  /   \
 3     2
 |
 4

加入后,“ 1”的等級為3, rank_old(1) + 1如預期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM