#include<iostream>
#include<cassert>
#include<ctime>
using namespace std;
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 >= 0 && p < count);
while (p != parent[p])
{
p = parent[p];
}
return p;
}
bool isConnected(int p, int q)
{
return find(p) == find(q);
}
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];
}
}
};
void testUF03(int n)
{
srand(time(NULL));
UnionFind uf = UnionFind(n);
for (int i = 0; i < n; i++)
{
int a = rand() % n;
int b = rand() % n;
uf.UnionElements(a, b);
}
for (int i = 0; i < n; i++)
{
int a = rand() % n;
int b = rand() % n;
cout << a <<"\t"<< b <<"\t"<< uf.isConnected(a, b) << endl;;
}
}
int main()
{
testUF03(100);
system("pause");
return 0;
}
010.并查集:实现方式③
最新推荐文章于 2020-05-02 21:00:00 发布