-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunionset
More file actions
31 lines (30 loc) · 703 Bytes
/
unionset
File metadata and controls
31 lines (30 loc) · 703 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
//union set
class Djset{
public:
int count;
vector<int> parent;
vector<int> rank;
Djset(int n): count(n){
for (int i = 0; i < n; i++){
parent.push_back(i);
rank.push_back(0);
}
}
int find(int x){
if (x == parent[x]) return x;
else{parent[x] = find(parent[x]);}
return parent[x];
}
bool merge(int x, int y){
int rx = find(x);
int ry = find(y);
if (ry != rx){
if (rank[rx] < rank[ry]){swap(rx, ry);}
parent[ry] = rx;
count --;
if (rank[rx] == rank[ry]){rank[rx] ++;}
return false;
}
return true;
}
}