#include<iostream>
#include<cassert>
#include<ctime>
using namespace std;
class UnionFind
{
private:
int* parent;
int count;
public:
UnionFind(int n)
{
count = n;
parent = new int[n];
for (int i = 0; i < n; i++)
{
parent[i] = i;
}
}
~UnionFind()
{
delete[] parent;
}
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;
}
parent[pRoot] = qRoot;
}
};
void testUF02(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()
{
testUF02(100);
system("pause");
return 0;
}
009.并查集:实现方式②
最新推荐文章于 2022-10-12 00:39:00 发布