集合
2017-08-10 本文已影响0人
日常表白结衣
集合的表示:
树结构表示集合,树的每个节点代表一个集合元素;双亲表示法,孩子指向双亲,父节点为数组下标

/* 集合 */
#define MaxSize 10
typedef int Elementtype;
typedef struct{
Elementtype Data;
int parent;
}SetType;
int Find(SetType S[],Elementtype X)
{
int i;
//查找元素X
for(i=0;i<MaxSize&&S[i].Data!=X;i++);
if(i>=MaxSize) return -1;
//查找元素X的根节点在数组的下标
for( ; S[i].parent>=0;i=S[i].parent);
return i;
}
/* 并运算,其中一个根节点的父节点指针设置成另一个根节点的数组下标 */
void Union(SetType S[],Elementtype X1,Elementtype X2)
{
int Root1,Root2;
Root1=Find(S,X1);
Root2=Find(S,X2);
if(Root1!=Root2) S[Root2].parent=Root1;
}