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; }
相关文章推荐
- 【数据结构】图的广度优先搜索
- linux的I/O多路转接select的fd_set数据结构和相应FD_宏的实现分析
- 数据结构 字符串模式匹配之BF算法
- 数据结构和算法
- 数据结构—二叉搜索树的创建、结点的插入和删除
- 排序算法一览
- 数据结构中排序算法-插入排序(1)
- MySQL索引背后的数据结构及算法原理
- 关于排序的稳定性与不稳定性
- 数据结构与算法分析Java版练习1.7
- 数据结构基础笔记(一)【严蔚敏】
- 数据结构与算法分析Java版练习1.6
- 为算法考试做准备--图的实现及广度和深度优先搜索实现
- 并查集算法介绍
- 数据结构Java实现04----循环链表、仿真链表
- MySQL索引背后的数据结构及算法原理
- Windows内核编程基础篇之常见内核数据结构
- 过河卒
- 数据结构算法演示
- 数据结构之---C语言实现斐波那契查找