Skip to content

Commit 06bc5a9

Browse files
committed
按秩合并并查集
1 parent eee4ce8 commit 06bc5a9

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

tags/DataStructure/并查集.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# 并查集
2+
3+
> 并查集是一类优雅的,解决连通块问题的数据结构
4+
5+
### 并查集模板
6+
7+
路径压缩+按秩合并版本
8+
9+
```c
10+
template <class T>
11+
struct UF {
12+
vector<T> rk;
13+
vector<T> fa;
14+
T count = 0;
15+
UF (T n){
16+
for(int i = 0; i < n; i++){
17+
rk.push_back(1); fa.push_back(i);
18+
}
19+
count = n;
20+
}
21+
T find(T x){return fa[x] == x? x: (fa[x] = find(fa[x]));}
22+
void merge(T x, T y){
23+
x = find(x), y = find(y);
24+
if(x != y) count--;
25+
if(rk[x] <= rk[y]) fa[x] = y;
26+
else fa[y] = x;
27+
if(rk[x] == rk[y]) rk[y]++;
28+
}
29+
void isolate(T x){
30+
if(x != fa[x]){
31+
fa[x] = x;
32+
count++;
33+
rk[x] = 1;
34+
}
35+
}
36+
T get() const {return count;}
37+
};
38+
```
39+
40+
实测似乎在很多情况下都不会卡按秩合并,所以,也可以用更加简单的一个版本:
41+
42+
```c
43+
int fa[100010];
44+
int find(int x){
45+
return fa[x] == x? fa[x]: (fa[x] = find(fa[x]));
46+
}
47+
void merge(int x, int y){
48+
fa[find(x)] = fa[find(y)];
49+
}
50+
```
51+
52+
并查集可以快速解决连通块问题,计数连通块个数,确定一个区域的元素是否位于同一个连通块

0 commit comments

Comments
 (0)