Quick-Find

Quick-find solution to connectivity problem

#include <iostream>
using namespace std;

const int N = 100;

int main()
{
	int i = 0;
	int temp = 0;
	int p, q, id[N];

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

	while (cin>>p>>q)
	{
		// quick find
		if (id[p] == id[q])
		{
			continue;
		}

		// slow union
		for (temp=id[p], i=0; i<N; i++)
		{
			if (id[i] == temp)
			{
				id[i] = id[q];
			}
		}

		cout<<p<<"  "<<q<<endl;
	}
	system("pause");
	return 0;
}

 

quick-find(slow union)测试用例图解:

Quick-Find_第1张图片

 

quick-find(slow union)树状表示图解如下:

Quick-Find_第2张图片

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