-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnionFind.cpp
More file actions
56 lines (44 loc) · 1021 Bytes
/
UnionFind.cpp
File metadata and controls
56 lines (44 loc) · 1021 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef long long int ll;
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef long long int ll;
class UnionFind {
private:
vi p, rank;
int n;
public:
UnionFind(int N) {
rank.assign(N, 0);
p.assign(N, 0);
for(int i = 0; i < N; ++i) p[i] = i;
n = N;
}
int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); } //with path compression
bool sameSet(int i, int j) { return (findSet(i) == findSet(j)); }
void UnionSet(int i, int j) {
if(!sameSet(i, j)) {
int x = findSet(i), y = findSet(j);
if(rank[x] > rank[y]) p[y] = x;
else {
p[x] = y;
if(rank[x] == rank[y]) { rank[y]++; }
}
}
}
int countSets() {
set<int> sets;
for(int i = 0; i < n; ++i) {
sets.insert(p[i]);
}
return (int)sets.size();
}
};
int main() {
return 0;
}