Weighted version of quick union

Weighted version of quick union

深刻理解代码中数组sz[]所起的权重的作用

#include <iostream>
using namespace std;

const int N = 100;

int main()
{
	int i, j;
	int p, q;
	int id[N], sz[N];  // 数组sz[]表示子树中节点的数量

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

	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;
		}

		// weighted version of quick union
		if (sz[i] < sz[j])
		{
			id[i] = j;
			sz[j] += sz[i];
		}
		else
		{
			id[j] = i;
			sz[i] += sz[j];
		}

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

	system("pause");
	return 0;
}


quick union测试用例图解:

Weighted version of quick union_第1张图片


Tree representation of weighted quick union

Weighted version of quick union_第2张图片


weighted quick union(worst case)

Weighted version of quick union_第3张图片

你可能感兴趣的:(Weighted version of quick union)