并查集:实现方式③

#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;
}
发布了27 篇原创文章 · 获赞 23 · 访问量 262

猜你喜欢

转载自blog.csdn.net/dosdiosas_/article/details/105556385