int father[MAX];
int rank[MAX];//集合深度
/*
int Find(int x){//查找
int r=x,i,j;
while(father[r]!=r)
r=father[r];
i=x;
while(i!=r){//路径压缩
j=father[i];
father[i]=r;
i=j;
}
return r;
}
*/
int Find(int x){//递归,回溯时路径压缩
if(x!=father[x])
father[x]=Find(father[x]);
return father[x];
}
/*
void Union(int x,int y){//合并
int fx=Find(x);
int fy=Find(y);
if(fx!=fy)
father[fx]=fy;
}
*/
void Union(int x,int y){//深度小的集合合并到深度大的集合,查找和路径压缩时更快
//rank[]初始为1
int fx=Find(x);
int fy=Find(y);
if(fx==fy)
return;
if(rank[fx]>rank[fy]){
father[fy]=fx;
if(rank[fy]+1>rank[fx])
rank[fx]=rank[fy]+1;
}
else{
father[fx]=fy;
if(rank[fx]+1>rank[fy])
rank[fy]=rank[fy]+1;
}
}
并查集
最新推荐文章于 2020-03-26 20:29:47 发布