Weighted quick union with Path compression by halving

路径压缩:在并集算法中,只要让我们接触到的所有对象都指向新树的根。

Path compression case 1: 6  1

Weighted quick union with Path compression by halving_第1张图片

 

Path compression case 2: 6  8
Weighted quick union with Path compression by halving_第2张图片

 

对分路径压缩并查集算法本质:每个节点在连通的过程中,跳到上一级树,指向上一级的节点,从而实现路径压缩。(即跳过找父节点,直接找爷爷节点)

#include <iostream>
using namespace std;

const int N = 100;

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

	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])
		{
			id[i] = id[id[i]];  // 跳到上一级树,指向上一级的节点,以两倍速度找到根节点
		}

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

		if (i == j)
		{
			continue;
		}

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

 

Path compression by halving

Weighted quick union with Path compression by halving_第3张图片

你可能感兴趣的:(Weighted quick union with Path compression by halving)