并查集问题——合并集合、查某元素属于什么集合
集合存储的实现:使用树结构
查找某个元素所在集合
typedef struct Node{
ElementType Data;
int parent;
}SetType;
int Find(SetType S[],ElementType X)
{
/* 在数组S中查找值为X的元素所属的集合 */
/* MaxSize是全局变量,为数组S的最大长度 */
int i;
for(i=0;i<MaxSize&&S[i].Data!=X;i++);
if(i==MaxSize) return -1;//未找到
else
for(;S[i].parent>=0;i=S[i].parent);/*如果是斜树,效率低*/
return i;
}
/*压缩路径方法*/
#define MAXN 1000 /* 集合最大元素个数 */
typedef int ElementType; /* 默认元素可以用非负整数表示 */
typedef int SetName; /* 默认用根结点的下标作为集合名称 */
typedef ElementType SetType[MAXN]; /* 假设集合元素下标从0开始,数组内存储该元素所属集合 */
SetName Find(SetType S, ElementType X )
{
if(S[X]<0)return X;
else return S[X]=Find(S,S[X]);//压缩该元素到总集合的距离
}
并集运算
void Union(SetType S,SetName root1,SetName root2)
{
/*根结点数组元存储该集合元素数的负值*/
/*小集合并入大集合中*/
/*操作有:修改小集合所在集合;修改大集合内元素数*/
if(S[root1]<S[root2]){//root1为大集合
S[root1]+=S[root2];
S[root2]=root1;}
else{
S[root2]+=S[root1];
S[root1]=root2;}
}