-
Notifications
You must be signed in to change notification settings - Fork 8
/
0. Disjoint Set.cpp
139 lines (116 loc) · 2.02 KB
/
0. Disjoint Set.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <bits/stdc++.h>
using namespace std;
// BARE BONE DSU
class DisjointSet
{
private:
vector<int> parent;
vector<int> rank;
public:
DisjointSet(int N)
{
parent.assign(N, -1);
rank.assign(N, 1);
}
int find(int u)
{
if (parent[u] == -1)
return u;
return parent[u] = find(parent[u]);
}
void Union(int u, int v)
{
u = find(u);
v = find(v);
if (u == v)
return;
parent[v] = u;
rank[u] += rank[v];
}
};
// == DETAILED UNION FIND :-) ==
class DisjointSet
{
private:
vector<int> parent;
vector<int> rank;
public:
DisjointSet(int N)
{
parent.resize(N, -1);
rank.resize(N, 1);
}
// Find the parent of the Disjoint Set
int find(int u)
{
if (parent[u] == -1)
return u;
else
return parent[u] = find(parent[u]);
}
// Merge Two Disjoint Sets
void Union(int u, int v)
{
u = find(u);
v = find(v);
if (u == v)
return;
else
{
if (rank[u] > rank[v])
{
parent[v] = u;
rank[u] += rank[v];
}
else
{
parent[u] = v;
rank[v] += rank[u];
}
}
}
// Checks whether two elements are in the same set of not
bool check(int u, int v)
{
return (find(u) == find(v)) ? true : false;
}
// Count the numeber of Disjoint Sets
int getDisjointSets()
{
return count(parent.begin(), parent.end(), -1);
}
// Get the size of the Disjoint Set
int getRank(int u)
{
return rank[u];
}
// Get the Largest Disjoint Set
int getMaxRank()
{
return *max_element(rank.begin(), rank.end());
}
};
class DisjointSetSimple
{
private:
vector<int> parent;
DisjointSetSimple(int n)
{
parent.assign(n, -1);
}
int find(int node)
{
if (parent[node] == -1)
return node;
return parent[node] = find(parent[node]);
}
void Union(int u, int v)
{
u = find(u), v = find(v);
if (u == v)
return;
else
// we can use rank compression here to make it more efficient
parent[u] = v;
}
};