Quick-Union

Quick-union solution to connectivity problem

#include <iostream>
using namespace std;

const int N = 100;

int main()
{
	int i, j;
	int p, q, id[N];

	for (i=0; i<N; i++)
	{
		id[i] = i;
	}

	while (cin>>p>>q)
	{
		// find the root of p
		for (i=p; i != id[i]; i=id[i])
		{
		}

		// find the root of q
		for (j=q; j != id[j]; j=id[j])
		{
		}

		if (i == j)
		{
			continue;
		}

		// quick union
		id[i] = j;

		cout<<p<<"  "<<q<<endl;
	}

	system("pause");
	return 0;
}


quick union测试用例图解如下:

Quick-Union_第1张图片

 

quick union树表示图解如下:

你可能感兴趣的:(Quick-Union)