- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion_find.cpp
More file actions
Latest commit
42 lines (32 loc) · 800 Bytes
/
Copy pathunion_find.cpp
File metadata and controls
42 lines (32 loc) · 800 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<numeric>
#include<vector>
usingnamespacestd;
// Disjoint Set Union (Union-Find)
structDSU {
vector<int> parent;
vector<int> size; // 그룹 크기 추적
DSU(int n) {
parent.resize(n + 1);
iota(parent.begin(), parent.end(), 0); // 0, 1, 2, ...
size.assign(n + 1, 1);
}
intfind(int x) {
if (parent[x] == x)
return x;
return parent[x] = find(parent[x]); // 경로 압축
}
boolunite(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
returnfalse;
// Union by Size (더 큰 쪽으로 합치기)
if (size[a] < size[b])
swap(a, b);
parent[b] = a;
size[a] += size[b];
returntrue;
}
boolsame(int a, int b) { returnfind(a) == find(b); }
intgetSize(int x) { return size[find(x)]; }
};