And check: the way to achieve ①

In order to introduce the graph theory algorithm in the future, here are several implementations of the union algorithm. However, this implementation is not general, but here is just to make some foreshadowing later.

#include<iostream>
#include<cassert>
#include<ctime>

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;
}
Published 27 original articles · won 23 · views 264

Guess you like

Origin blog.csdn.net/dosdiosas_/article/details/105555762