Union-Find 按大小求并算法

#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) {
      int root1 = Find(p);
      int root2 = 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;
}

未完待续
更详细请参见 这里
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值