-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunion_find.cpp
More file actions
42 lines (32 loc) · 800 Bytes
/
union_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>
using namespace std;
// Disjoint Set Union (Union-Find)
struct DSU {
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);
}
int find(int x) {
if (parent[x] == x)
return x;
return parent[x] = find(parent[x]); // 경로 압축
}
bool unite(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return false;
// Union by Size (더 큰 쪽으로 합치기)
if (size[a] < size[b])
swap(a, b);
parent[b] = a;
size[a] += size[b];
return true;
}
bool same(int a, int b) { return find(a) == find(b); }
int getSize(int x) { return size[find(x)]; }
};