集合的定义与并查操作

  集合的定义与并查操作。

 1 #define MAXN 1000                  /* 集合最大元素个数 */
 2 typedef int ElementType;           /* 默认元素可以用非负整数表示 */
 3 typedef int SetName;               /* 默认用根结点的下标作为集合名称 */
 4 typedef ElementType SetType[MAXN]; /* 假设集合元素下标从0开始 */
 5  
 6 void Union( SetType S, SetName Root1, SetName Root2 )
 7 { /* 这里默认Root1和Root2是不同集合的根结点 */
 8     /* 保证小集合并入大集合 */
 9     if ( S[Root2] < S[Root1] ) { /* 如果集合2比较大 */
10         S[Root2] += S[Root1];     /* 集合1并入集合2  */
11         S[Root1] = Root2;
12     }
13     else {                         /* 如果集合1比较大 */
14         S[Root1] += S[Root2];     /* 集合2并入集合1  */
15         S[Root2] = Root1;
16     }
17 }
18  
19 SetName Find( SetType S, ElementType X )
20 { /* 默认集合元素全部初始化为-1 */
21     if ( S[X] < 0 ) /* 找到集合的根 */
22         return X;
23     else
24         return S[X] = Find( S, S[X] ); /* 路径压缩 */
25 }
原文地址:https://www.cnblogs.com/wgxi/p/10003112.html