并查集
并查集模板
包含路径压缩+小挂大
const int MAXN = 1e5 + 1;
int father[MAXN]; // 存父亲节点 father[1] =2 指的是1节点的父亲为2
int size[MAXN]; // 存每个集合的大小
int stack[MAXN]; //
int n;
// 建立并查集
void build(){
for(int i = 0; i <= n; i ++ ){
father[i] = i;
size[i] = 1;
}
}
// 查找元素
int find(int i){
// 沿途收集了几个点
int size = 0;
while(i != father[i]){
stack[size ++ ] = i;
i = father[i];
}
// 沿途节点收集好了,i已经跳到代表节点了
while(size > 0){
father[stack[-- size ]] = i;
}
return i;
}
bool isSameSet(int x, int y){
return find(x) == find(y);
}
void union(int x, int y){
int fx = find(x);
int fy = find(y);
if(fx != fy){
if(size[fx] >= size[fy]){
size[fx] += size[fy];
father[fy] = fx;
}else{
size[fy] += size[fx];
father[fx] = fy;
}
}
}
并查集模板(精简版)
路径压缩
const int MAXN = 1001;
int father[MANX];
int n;
void build(){
for(int i = 0; i <= n; i ++ ){
father[i] = i;
}
}
int find(int i){
if(i != father[i]){
father[i] = find(father[i]); // 路径压缩
}
return father[i];
}
bool isSameSet(int x, int y){
return find(x) == find(y);
}
void union(int x, int y){
father[find(x)] = find(y);
}
标签:int,fy,查集,father,fx,size
From: https://www.cnblogs.com/hnu-hua/p/18179456