008.并查集:实现方式①

为了日后介绍图论算法的方便这里给出几种并查集算法的实现方式,然而,这样的实现方式并不具有一般性,这里不过是为了后面做一些铺垫罢了。

#include
#include
#include

using namespace std;

class UnionFind
{
private:
	int* id;
	int count;
public:
	UnionFind(int n)
	{
		count = n;
		id = new int[n];
		for (int i = 0; i < n; i++)
		{
			id[i] = i;
		}
	}

	~UnionFind()
	{
		delete[] id;
	}

	int find(int p)
	{
		assert( p >= 0&&p<count);
		return id[p];
	}

	bool isConnected(int p, int q)
	{
		return find(p) == find(q);
	}

	void unionElements(int p, int q)
	{
		int pID = find(p);
		int qID = find(q);

		if (pID == qID)
		{
			return;
		}

		for (int i = 0; i < count; i++)
		{
			if (id[i] == pID)
			{
				id[i] = qID;
			}
		}
	}
};


void testUF01(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()
{
	testUF01(100);
	system("pause");
	return 0;
}

你可能感兴趣的:(数据结构)