小编给大家分享一下c++并查集优化的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
基于size的优化是指:
当我们在指定由谁连接谁的时候,size数组维护的是当前集合中元素的个数,让数据少的指向数据多的集合中
基于rank的优化是指:
当我们在指定由谁连接谁的时候,rank数组维护的是当前集合中树的高度,让高度低的集合指向高度高的集合
运行时间是差不多的:
基于size的代码: UnionFind3.h
#ifndef UNION_FIND3_H_
#define UNION_FIND3_H_
#include<iostream>
#include<cassert>
namespace UF3
{
class UnionFind
{
private:
int* parent;
int* sz; //sz[i]就表示以i为根的集合中元素的个数
int count;
public:
UnionFind(int count)
{
this->count = count;
parent = new int[count];
sz = new int[count];
for(int i = 0 ; i < count ; i++)
{
parent[i] = i;
sz[i] = 1;
}
}
~UnionFind()
{
delete [] parent;
delete [] sz;
}
int find(int p)
{
assert(p < count && p >= 0);
while( p != parent[p]) //这个是写到find里面的
{
p = parent[p];
}
return p;
}
void unionElements(int p , int q)
{
int pRoot = find(p);
int qRoot = find(q);
if( pRoot == qRoot)
return;
if(sz[pRoot] < sz[qRoot])
{
parent[pRoot] = qRoot;
sz[qRoot] += sz[pRoot];
}
else
{
parent[qRoot] = pRoot;
sz[pRoot] += sz[qRoot];
}
}
bool isConnected(int p , int q)
{
return find(p) == find(q);
}
};
};
#endif
基于rank的代码: UnionFind4.h
#ifndef UNION_FIND4_H_
#define UNION_FIND4_H_
#include<iostream>
#include<cassert>
namespace UF4
{
class UnionFind
{
private:
int* parent;
int* rank; //rank[i]就表示以i为根的集合的层数
int count;
public:
UnionFind(int count)
{
this->count = count;
parent = new int[count];
rank = new int[count];
for(int i = 0 ; i < count ; i++)
{
parent[i] = i;
rank[i] = 1;
}
}
~UnionFind()
{
delete [] parent;
delete [] rank;
}
int find(int p)
{
assert(p < count && p >= 0);
while( p != parent[p]) //这个是写到find里面的
{
p = parent[p];
}
return p;
}
void unionElements(int p , int q)
{
int pRoot = find(p);
int qRoot = find(q);
if( pRoot == qRoot)
return;
if(rank[pRoot] < rank[qRoot])
{
parent[pRoot] = qRoot;
}
else if( rank[pRoot] > rank[qRoot] )
{
parent[qRoot] = pRoot;
}
else
{
parent[pRoot] = qRoot; //这里谁指向谁无所谓
rank[qRoot] ++;
}
}
bool isConnected(int p , int q)
{
return find(p) == find(q);
}
};
};
#endif
剩下的头文件和main文件在上一个并查集的博客中有,就不再粘贴出来了
以上是“c++并查集优化的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。