【并查集模板】
int find(int x) {
if(x!=pre[x]) pre[x]=find(pre[x]);
return pre[x];
}
void merge(int x,int y) {
int a=find(x);
int b=find(y);
if(a!=b) pre[a]=b;
}
【带权并查集模板】
● 带权并查集的 find() 函数
int find(int x) {
if(x!=pre[x]) {
int t=pre[x];
pre[x]=find(pre[x]);
val[x]+=val[t]; //Some operation
}
return pre[x];
}
● 带权并查集的 merge() 函数
把 x 的集合连向 y 的集合,显然需要 pre[fx]=fy,然后依据向量运算规则,易得从 fx 指向 fy 的权值为 Vy-Vx+s
void merge(int x,int y,int s) {
if (find(x)!=find(y)) {
pre[find(x)]=find(y);
val[find(x)]=val[y]-val[x]+s; //Some operation
}
}
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/120131297
https://blog.csdn.net/hnjzsyjyj/article/details/120120591
https://blog.csdn.net/qq_44691917/article/details/104684859
https://blog.csdn.net/qq_44691917/article/details/103943428