int FindSet(int x){
int px = x;
while(px != p[px])//当px不是树根,就一直往上冒
px = p[px];
while(x != px){//做一点优化,把路径上的结点的父结点全部设为根
int temp = p[x];
p[x] = px;
x = temp;
}
return px;
}
void UnionSet(int x, int y){
x = FindSet(x);
y = FindSet(y);
if(Rank[x] > Rank[y])
p[y] = x;
else{
p[x] = y;
if(Rank[x] == Rank[y])
Rank[y]++;
}
}
网友评论