/*****/并查集

在一个有N个元素的集合问题中,我们通常是让每个元素构成一个单元素的集合,然后按一定顺序将属于同一集合的元素进行合并。在此过程中要不断的查询某个元素归属于哪个集合,适合于描述这类问题的抽象数据类型我们称之为并查集。
实际应用:
已知有n个人和m对好友关系,并且这些好友关系存储在r里面,如果两个人是直接或间接的好友,则认为他们属于同一个朋友圈。
n=5,m=3,r={{1,2},{2,3},{4,5}}求出这n个人里面一共有多少个朋友圈。
这里写图片描述
要求上面题中朋友圈的个数,只需要求出并查集中负数的个数就行了,最后别忘了减去0这个位置就行了。

class UnionSet  
{  
public:  
       UnionSet(int n)  
              :_size(n+1)  
       {  
              _a = new int[n+1];  
              memset(_a,-1,sizeof(int)*(n+1));   //memset只有在0和-1的时候1个字节与4个字节所得到的结果是相同的  
       }  
       ~UnionSet()  
       {  
              delete[] _a;  
       }  
       void Merge(int x1,int x2)  
       {  
              int root1 = GetRoot(x1);  
              int root2 = GetRoot(x2);  
              if (root1 != root2)           //如果这两个元素不再一个集合中  
              {  
                     _a[root1] += _a[root2];    //把root2的值加到根节点处  
                     _a[root2] = root1;         //让root2处存放根节点的下标  
              }  
       }  
       int CountSet()  
       {  
              int count = 0;  
              for (size_t i = 0; i < _size; ++i)  
              {  
                     if (_a[i] < 0)  
                           count++;  
              }  
              return count - 1;  
       }  
protected:  
       int GetRoot(int index)  
       {  
              int root = index;  
              while (_a[root] >= 0)  
              {  
                     root = _a[root];  
              }  
              return root;  
       }  
private:  
       int *_a;  
       size_t _size;  
};  


void TestUnionSet()  
{  
       const int n = 5;  
       const int m = 6;  
       int r[m][2] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 3 }, { 5, 4 }, {3,5} };  
       UnionSet set(n);  
       for (int i = 0; i < m;i++)  
       {  
              set.Merge(r[i][0],r[i][1]);  
       }  
       cout << set.CountSet() << endl;  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值