Union-Find 按大小求并算法

来源:互联网 发布:jenkins php持续集成 编辑:程序博客网 时间:2024/06/18 08:52
#include
#include

using namespace std;

class UF{
  public:
    UF(int size): vec(size),parent(size) {
      for(int i = 0; i < size; i++) {
       vec[i] = i;
       parent[i] = -1;
     }
    }
    void Union(int p, int q){
      introot1 = Find(p);
      introot2 = Find(q);
     //将小树链接到大树,大小则由数的结点个数确定
      if(root1 > root2) { // 例如-2 > -3说明要将root1链接到root2上面
       parent[root2] += parent[root1];//更新大树的结点个数
       parent[root1] = root2; //将树1链接到树2
      }else {
       parent[root1] += parent[root2];
       parent[root2] = root1;
     }
    }
    int Find(int x) {
      if(parent[x] < 0) //递归直到x的父节点为负数
       return x;
     else
       return parent[x] = Find(parent[x]);//带有路径压缩功能,若本次找到组号,那么递归找到组号后直接赋值给parent[x],下次查找则能在O(1)内完成
  }
    int count(int x) {
      int c= parent[Find(x)];
     return -c;
    }
  private:
    vector vec;
    vector parent;//parent有两个作用,一个是指示集合中的个数,另外若parent[x]为负数,x则为集合 //中的组号
};

int main() {
  UF uf(10);
  uf.Union(2, 3);
  uf.Union(6, 7);
  uf.Union(0, 1);
  uf.Union(1, 2);
  uf.Union(3, 6);
  cout <<uf.Find(0) << endl;
  cout <<uf.Find(1) << endl;
  cout <<uf.Find(2) << endl;
  cout <<uf.Find(3) << endl;
  cout <<uf.Find(6) << endl;
  cout <<uf.Find(7) << endl;
  cout <<uf.count(0) << endl;
  cout <<uf.count(1) << endl;
  cout <<uf.count(2) << endl;
  cout <<uf.count(3) << endl;
  cout <<uf.count(6) << endl;
  cout <<uf.count(7) << endl;
  return 0;
}

未完待续
更详细请参见这里
原创粉丝点击