按大小求并和按高度求并,保证所有的树的深度最多是O(logN).
定理:M次Union和Find的运行时间为O(MlogN).
Find操作和表示x的节点的深度成正比。
//不相交集ADT
const int NumSets = 8;
//不相交集合的类型声明
typedef int DisjointSet[NumSets+1];
typedef int SetType;
//初始化例程
void InitializeDisjointSet(DisjointSet S){
//int num_djsets = num_sets + 1;
//S = new int[num_sets];
for (int i = NumSets; i >0 ; i--){ //S[0]没有初始化为0,即,数组中的位置0并没有使用。 S[1]代表x=1,S[2]代表x=2...
S[i] = 0;
}
}
//Find例程
SetType FindDisjointSet(int x, DisjointSet S){
if (S[x] <= 0){
return x;
}
else{
return FindDisjointSet(S[x], S);
}
//return S[x];
}
//Union例程,不是最好的方法
//使第二棵树成为第一棵树的子树
//约定:Union(X,Y)后,新的根是X
void SetUnionSimple(DisjointSet S,SetType root1, SetType root2){
S[root2] = root1;
}
//按高度求并的Union例程
void SetUnion(DisjointSet S, SetType root1, SetType root2){
if (S[root2] < S[root1]){ //root2比root1深
S[root1] = root2; //哪个根深就继续用哪个作为新根
}
else{
if (S[root2] == S[root1]){
S[root1]--; //使root1的深度+1
}
S[root2] = root1;
}
}
测试实例:
//test disjointset
DisjointSet S;
InitializeDisjointSet(S);
cout << S[0] << endl;
cout << S[1] << endl;
SetType st=FindDisjointSet(5, S);
cout << "find disjointset:" << endl;
cout << st << endl;
SetUnion(S, 5, 7);
if (FindDisjointSet(5, S) == FindDisjointSet(6, S)){
cout << "they are equal!" << endl;
}
else{
cout << "they are not equal!" << endl;
}
SetUnion(S, 5, 3);
if (FindDisjointSet(3, S) == FindDisjointSet(7, S)){
cout << "they are equal!" << endl;
}
else{
cout << "they are not equal!" << endl;
}
路径压缩(path compression):从x到根的路径上的每一个节点都使它的父节点变成根。
唯一的变化是使得S[x]等于Find返回的值。对通向根的路径上的每一个节点递归的实现路径压缩。
//路径压缩的Find例程
SetType FindDisjointSet(int x, DisjointSet S){
if (S[x] <= 0){
return x;
}
else{
return S[x] = FindDisjointSet(S[x], S);
}
//return S[x];
}
路径压缩与按大小求并完全兼容,两个例程可以同时实现。
路径压缩不完全与按高度求并兼容,因为路径压缩可以改变树的高度。