并查集
验证链接:https://www.luogu.com.cn/problem/P3367
同时使用按秩合并和路径压缩的写法,由于使用了按秩合并,所以路径压缩使用递归并不会爆栈。
struct DisjointSet {
static const int MAXN = 200000 + 10;
int fnd[MAXN], siz[MAXN];
void Init(int n) {
for(int i = 1; i <= n; i++)
fnd[i] = i, siz[i] = 1;
}
int Find(int x) {
return (fnd[x] == x) ? x : fnd[x] = Find(fnd[x]);
}
int Size(int x) {
x = Find(x);
return siz[x];
}
int Merge(int x, int y) {
x = Find(x), y = Find(y);
if(x == y)
return 0;
if(siz[x] < siz[y])
swap(x, y);
fnd[y] = x;
siz[x] += siz[y];
return x;
}
} ds;
并查集维护可删除链表
struct DisjointSet {
static const int MAXN = 200000 + 10;
int prev[MAXN], next[MAXN];
void Init(int n) {
for(int i = 0; i <= n + 1; ++i)
prev[i] = i, next[i] = i;
}
int Prev(int x) {
return (prev[x] == x) ? x : prev[x] = Prev(prev[x]);
}
int Next(int x) {
return (next[x] == x) ? x : next[x] = Next(next[x]);
}
void Delete(int x) {
prev[x] = Prev(x - 1), next[x] = Next(x + 1);
}
} ds;