您的位置:首页 > 理论基础 > 数据结构算法

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

2015-08-29 17:25 369 查看
/*
* 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: