• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C++实现并查集

c++ 搞代码 4年前 (2022-01-06) 35次浏览 已收录 0个评论

这篇文章主要为大家详细介绍了C++实现并查集,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C++实现并查集的具体代码,供大家参考,具体内容如下

 #include  #include  #include  using namespace std; class UnionFind{ private: vector parent; int count; //优化,记录p和q所在组的深度,在合并时将深度小的结点的根指向深度大的结点的根 vector rank; public: UnionFind(int count){ parent.resize(count); rank.resize(count); this->count = count; fo<mark style="color:transparent">来源gaodaimacom搞#代%码网</mark>r(int i = 0; i = 0 && p <count); if(p != parent[p]) parent[p] = find(parent[p]); return parent[p]; } bool isConnected(int p, int q){ return find(p) == find(q); } void unionElement(int p, int q){ int pRoot = find(p), qRoot = find(q); if(pRoot == qRoot) return; if(rank[pRoot] <rank[qRoot]) parent[pRoot] = qRoot; else if(rank[qRoot] <rank[pRoot]) parent[qRoot] = pRoot; else{ //两者的rank相等 parent[pRoot] = qRoot; rank[qRoot] += 1; } } };

小编再补充一段代码,之前收藏的一段代码:

 #include  using namespace std; class UF  { //cnt is the number of disjoint sets. //id is an array that records distinct identity of each set,when two sets are merged ,their id will be same. //sz is an array that records the child number of each set including the set self. int *id, cnt, *sz; public: // Create an empty union find data structure with N isolated sets. UF(int N)  { cnt = N; id = new int[N]; sz = new int[N]; for (int i = 0; i<N; i++) { id[i] = i; sz[i] = 1; } } ~UF() { delete[] id; delete[] sz; } // Return the id of component corresponding to object p. int find(int p) { if (p != id[p]){ id[p] = find(id[p]); } return id[p]; } // Replace sets containing x and y with their union. void merge(int x, int y) { int i = find(x); int j = find(y); if (i == j) return; // make smaller root point to larger one if (sz[i] <sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } cnt--; } // Are objects x and y in the same set? bool connected(int x, int y)  { return find(x) == find(y); } // Return the number of disjoint sets. int count() { return cnt; } }; void main(){ UF test(5); test.merge(2, 3); test.merge(3, 4); cout << test.find(4); cout << test.count(); }

同时谢谢这位作者的分享

以上就是C++实现并查集的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++实现并查集
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址