C源码@数据结构与算法->DisjointSet

/*
 * Disjoint set data structure.
 * All in one file because it's so short.
 */

#define FastAlg

#define NumSets (128)

#ifndef _DISJ_SET_H

typedef int DisjSet[NumSets + 1];
typedef int SetType;
typedef int ElementType;

void Initialize(DisjSet S);
void SetUnion(DisjSet S, SetType Root1, SetType Root2);
SetType Find(ElementType X, DisjSet S);

#endif /* _DISJ_SET_H */ 

void Initialize(DisjSet S)
{
	int i;

	for (i = NumSets; i > 0; --i)
	{
		S[i] = 0;
	}
}

#ifdef SlowAlg

/*
 * Assume Root1 and Root2 are roots,
 * union is a C keyword, so this routine is named SetUnion.
 */
void SetUnion(DisjSet S, SetType Root1, SetType Root2)
{
	S[Root2] = Root1;
}

SetType Find(ElementType X, DisjSet S)
{
	if (S[X] <= 0)
	{
		return X;
	}
	else
	{
		return Find(S[X], S);
	}
}

#else /* SlowAlg */

/*
* Assume Root1 and Root2 are roots,
* union is a C keyword, so this routine is named SetUnion.
*/
void SetUnion(DisjSet S, SetType Root1, SetType Root2)
{
	if (S[Root2] < S[Root1])	/* Root2 is deeper set */
	{							/* Make Root2 new root */
		S[Root1] = Root2;
	}
	else
	{
		if (S[Root1] == S[Root2])	/* Same Height */
		{							/* So update */
			S[Root1]--;
		}
		S[Root2] = Root1;
	}
}

SetType Find(ElementType X, DisjSet S)
{
	if (S[X] <= 0)
	{
		return X;
	}
	else
	{
		return S[X] = Find(S[X], S);
	}
}

#endif /* #ifdef SlowAlg */

#include 
   
   
    
    

int main()
{
	DisjSet S;
	int i, j, k, Set1, Set2;

	Initialize(S);

	k = 1;
	while (k <= 8)
	{
		j = 1;
		while (j <= NumSets)
		{
			Set1 = Find(j, S);
			Set2 = Find(j + k, S);
			SetUnion(S, Set1, Set2);
			j += 2 * k;
		}
		k *= 2;
	}

	for (i = 1; i < NumSets; ++i)
	{
		Set1 = Find(i, S);
		printf("%d**", Set1);
	}
	printf("\n");
	
	return 0;
}
   
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值