常规并查集模板
常规并查集
模板
#define Maxsize 100+1
int f[Maxsize];
void init(int n){
for(int i = 1; i <= n; i++)
f[i] = i;
}
int find_f(int a){
if(f[a] == a){
return a;
}else{
return f[a] = find_f(f[a]);
}
}
void union_f(int a,int b){
int af = find_f(a);
int bf = find_f(b);
f[bf] = af;
}
bool same_f(int a,int b){
return find_f(a) == find_f(b);
}
按秩合并
可以提高效率,减少路径压缩
#define Maxsize 100+1
int f[Maxsize];
int r[Maxsize];
void init(int n){
for(int i = 1; i <= n; i++){
f[i] = i;
r[i] = 0;
}
}
int find_f(int a){
if(f[a] == a){
return a;
}else{
return f[a] = find_f(f[a]);
}
}
int union_f(int a,int b){
int af = find_f(a);
int bf = find_f(b);
if(r[af] > r[bf]){
f[bf] = af;
}else if(r[af] < r[bf]){
f[af] = bf;
}else{
f[bf] = af;
r[af]++;
}
}
int same_f(int a,int b){
return find_f(a) == find_f(b);
}
---- suffer now and live the rest of your life as a champion ----