-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnion-Find.cpp
More file actions
42 lines (37 loc) · 792 Bytes
/
Union-Find.cpp
File metadata and controls
42 lines (37 loc) · 792 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
class UnionFind
{
private:
vector<int> parent;
public:
UnionFind(const int n):parent(vector<int>(n,-1))
{}
const int Find(const int p)
{
return parent[p] < 0 ? p : parent[p] = Find(parent[p]);
}
const void Merge(int p, int q);
const bool Belong(const int p, const int q)
{
return Find(p) == Find(q);
}
const int GetSize(const int p)
{
return -parent[Find(p)];
}
};
const void UnionFind::Merge(int p, int q)
{
p=Find(p);
q=Find(q);
if(p==q) return;
if(parent[p] < parent[q])
{
parent[p] += parent[q];
parent[q]=p;
}
else
{
parent[q] += parent[p];
parent[p]=q;
}
}